我有一个UILabel,它有两行文字的空间。有时,当文本太短时,此文本会显示在标签的垂直中心。
如何垂直对齐文本,使其始终位于UILabel的顶部?
我有一个UILabel,它有两行文字的空间。有时,当文本太短时,此文本会显示在标签的垂直中心。
如何垂直对齐文本,使其始终位于UILabel的顶部?
当前回答
如果您使用的是自动布局,请在代码或IB中将垂直内容HuggingPriority设置为1000。在IB中,您可能需要通过将其优先级设置为1然后删除来删除高度限制。
其他回答
您可以使用具有垂直对齐选项的UITextField代替UILabel:
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.userInteractionEnabled = NO; // Don't allow interaction
我花了一段时间阅读了代码,以及介绍页面中的代码,发现它们都试图修改标签的框架大小,这样就不会出现默认的中心垂直对齐。
然而,在某些情况下,我们确实希望标签占据所有这些空间,即使标签确实有太多文本(例如,高度相等的多行)。
在这里,我使用了另一种方法来解决这个问题,只需在标签末尾添加换行符(请注意,我实际上继承了UILabel,但这不是必须的):
CGSize fontSize = [self.text sizeWithFont:self.font];
finalHeight = fontSize.height * self.numberOfLines;
finalWidth = size.width; //expected width of label
CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;
for(int i = 0; i < newLinesToPad; i++)
{
self.text = [self.text stringByAppendingString:@"\n "];
}
试试这个!!太手动了,但对我来说很完美。
[labelName setText:@"This is just a demo"];
NSMutableString *yourString1= @"This is just a demo";
// breaking string
labelName.lineBreakMode=UILineBreakModeTailTruncation;
labelName.numberOfLines = 3;
CGSize maximumLabelSize1 = CGSizeMake(276,37); // Your Maximum text size
CGSize expectedLabelSize1 = [yourString1 sizeWithFont:labelName.font
constrainedToSize:maximumLabelSize1
lineBreakMode:labelName.lineBreakMode];
[labelName setText:yourString1];
CGRect newFrame1 = labelName.frame;
if (expectedLabelSize1.height>=10)
{
newFrame1.size.height = expectedLabelSize1.height;
}
labelName.frame = newFrame1;
创建新类
标签顶部对齐
.h文件
#import <UIKit/UIKit.h>
@interface KwLabelTopAlign : UILabel {
}
@end
.m文件
#import "KwLabelTopAlign.h"
@implementation KwLabelTopAlign
- (void)drawTextInRect:(CGRect)rect {
int lineHeight = [@"IglL" sizeWithFont:self.font constrainedToSize:CGSizeMake(rect.size.width, 9999.0f)].height;
if(rect.size.height >= lineHeight) {
int textHeight = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(rect.size.width, rect.size.height)].height;
int yMax = textHeight;
if (self.numberOfLines > 0) {
yMax = MIN(lineHeight*self.numberOfLines, yMax);
}
[super drawTextInRect:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, yMax)];
}
}
@end
Edit
下面是一个更简单的实现,它也做到了这一点:
#import "KwLabelTopAlign.h"
@implementation KwLabelTopAlign
- (void)drawTextInRect:(CGRect)rect
{
CGFloat height = [self.text sizeWithFont:self.font
constrainedToSize:rect.size
lineBreakMode:self.lineBreakMode].height;
if (self.numberOfLines != 0) {
height = MIN(height, self.font.lineHeight * self.numberOfLines);
}
rect.size.height = MIN(rect.size.height, height);
[super drawTextInRect:rect];
}
@end
在界面生成器中
将UILabel设置为最大可能文本的大小在属性检查器中将行设置为“0”
在您的代码中
设置标签的文本调用标签上的sizeToFit
代码段:
self.myLabel.text = @"Short Title";
[self.myLabel sizeToFit];