垂直对齐UILabel
我试图垂直对齐我的应用程序的UILabel视图中的文本。 问题是我想要文本垂直对齐顶部和标签的大小为280 x 150.我只能实现这两件事之一。 如果我删除线
[myLabel sizeToFit];
那么文本的对齐方式是可以的,但大小是混乱的。 但如果我添加上面的行,那么对齐就会搞砸了,但大小还是可以的。 我该如何解决这个问题。
我已经添加了下面的代码 -
CGRect labelFrame = CGRectMake(22, 50, 280, 150);
UILabel *myLabel = [[UILabel alloc] initWithFrame:labelFrame];
[myLabel setText:finalRecipe];
[myLabel setBackgroundColor: [UIColor lightGrayColor]];
[myLabel setNumberOfLines:0];
[myLabel sizeToFit];
[self.view addSubview:myLabel];
我是FXLabel的作者,虽然我不认识Manish,但我相信他在帮助(如果他为我做广告,我当然没有问他,我也没有付钱 - 对不起马尼什!)。
FXLabel的功能之一是它遵守标签的UIContentMode属性,如界面构建器中设置的那样。 这意味着你可以设置label.contentMode = UIViewContentModeTop; 将文本对齐到标签视图的顶部(这对于常规UILabel不起作用)。 相关示例如下:
https://github.com/nicklockwood/FXLabel/tree/master/Examples/Text%20Alignment
FXLabel是UILabel的一个嵌入式子类,所以我认为这对于提出的问题来说是一个很好的解决方案。 然而,如果海报宁愿在不使用第三方库(这是可以理解的)的情况下解决问题,那么下面是执行此操作的代码:
CGRect labelFrame = CGRectMake(22, 50, 280, 150);
UILabel *myLabel = [[UILabel alloc] initWithFrame:labelFrame];
[myLabel setText:finalRecipe];
[myLabel setBackgroundColor: [UIColor lightGrayColor]];
[myLabel setNumberOfLines:0];
CGFloat fontSize = 0.0f;
labelFrame.size = [myLabel.text sizeWithFont:myLabel.font
minFontSize:myLabel.minimumFontSize
actualFontSize:&fontSize
forWidth:labelFrame.width
lineBreakMode:myLabel.lineBreakMode];
myLabel.frame = labelFrame;
[self.view addSubview:myLabel];
注意:(这是未经测试的,所以如果有任何错别字,请致歉)
不要为此使用UILabel
。 使用UserInteractionEnabled = NO;
UIButton
UserInteractionEnabled = NO;
并且可以选择垂直或水平对齐文本。
干得好:
[btnDetail.titleLabel setNumberOfLines:5];
[btnDetail.titleLabel setLineBreakMode:NSLineBreakByCharWrapping];
[btnDetail setContentVerticalAlignment:UIControlContentVerticalAlignmentTop];
[btnDetail setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[btnDetail setUserInteractionEnabled:NO];
btnDetail.autoresizesSubviews = YES;
btnDetail.autoresizingMask = UIViewAutoresizingFlexibleWidth;
你需要继承UILabel。 尝试这个:
- (void)drawTextInRect:(CGRect)rect
{
CGSize sizeThatFits = [self sizeThatFits:rect.size];
rect.size.height = MIN(rect.size.height, sizeThatFits.height);
[super drawTextInRect:rect];
}
正如你发现的那样,UILabel将文本垂直居中在其范围内。 在这里,我们要求-sizeThatFits
输入文本块大小,并使用它来限制传递给UILabel的绘图矩形,以便从标签边界的顶部绘制文本。
你甚至可以像这样支持忽略的(叹气) contentMode
属性:
- (void)drawTextInRect:(CGRect)rect
{
CGSize sizeThatFits = [self sizeThatFits:rect.size];
if (self.contentMode == UIViewContentModeTop) {
rect.size.height = MIN(rect.size.height, sizeThatFits.height);
}
else if (self.contentMode == UIViewContentModeBottom) {
rect.origin.y = MAX(0, rect.size.height - sizeThatFits.height);
rect.size.height = MIN(rect.size.height, sizeThatFits.height);
}
[super drawTextInRect:rect];
}
这里还有其他一些解决方案和讨论:在UILabel中将文本垂直对齐
链接地址: http://www.djcxy.com/p/28193.html下一篇: Swift : align UILabel text in the top rather in the middle