我对UILabel
有这种特殊的行为。任何numberOfLines
都可以正常工作,除了1.如果我将行数设置为1,它将忽略我稍后设置的宽度。
我不明白为什么1行将它搞砸了......
这是我的代码
UILabel *label = [[UILabel alloc] init]; label.backgroundColor = [UIColor greenColor]; label.text = @"here is my label with lots of text to fill, here is my label with lots of text to fill"; label.frame = CGRectMake(20, 20, 100, 0); CGRect rect = label.frame; label.numberOfLines = 2; label.lineBreakMode = NSLineBreakByTruncatingTail; [self.view addSubview:label]; rect.size.width = 100; label.frame = rect; [label sizeToFit];
答案 0 :(得分:4)
使用此代码:
UILabel *label = [[UILabel alloc] init];
label.backgroundColor = [UIColor greenColor];
label.text = @"here is my label with lots of text to fill, here is my label with lots of text to fill";
label.frame = CGRectMake(20, 20, 100, 0);
label.numberOfLines = 3;
label.lineBreakMode = NSLineBreakByTruncatingTail;
[self.view addSubview:label];
[label sizeToFit];
CGRect rect = label.frame;
rect.size.width = 100;
label.frame = rect;
使用numberOfLines = 3
:
使用numberOfLines = 1
:
答案 1 :(得分:0)
如果您想使用numberOfLines = 1,那么您的文字将在一行中。所以请使用numberOfLines = 0
;
label.numberOfLines = 0;
并且无需再次定义标签框架,因此请删除这些声明。
CGRect rect = label.frame;
rect.size.width = 100;
label.frame = rect;
使用此代码,这是完美的..
UILabel *label = [[UILabel alloc] init];
label.backgroundColor = [UIColor greenColor];
label.text = @"here is my label with lots of text to fill, here is my label with lots of text to fill";
label.frame = CGRectMake(20, 20, 100, 0);
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByTruncatingTail;
[self.view addSubview:label];
[label sizeToFit];
答案 2 :(得分:-1)
将此用作:
UILabel *label = [[UILabel alloc] init];
label.backgroundColor = [UIColor greenColor];
label.text = @"here is my label with lots of text to fill, here is my label with lots of text to fill";
label.numberOfLines = 0;
CGSize labelSize = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(100 , 9999) lineBreakMode:label.lineBreakMode];
float lHeight = labelSize.height;
label.frame = CGRectMake(20, 20, 100, lHeight);
label.lineBreakMode = NSLineBreakByTruncatingTail;
[self.view addSubview:label];
编辑:- (void)sizeToFit
说明:
调整并移动接收器视图,使其只包含其子视图。 如果要调整当前视图的大小以使其占用最合适的空间,请调用此方法。具体的UIKit视图根据自己的内部需求调整自己的大小。在某些情况下,如果视图没有超视图,则可能会将其自身调整为屏幕边界。因此,如果您希望给定视图将其自身调整为其父视图,则应在调用此方法之前将其添加到父视图。
// [label sizeToFit];
希望它对你有所帮助。