1

我有这种特殊的行为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];
4

4 回答 4

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

图像1

numberOfLines = 1

图2

于 2013-05-06T13:51:47.933 回答
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];
于 2013-05-06T13:42:21.743 回答
0

是的,当 numberOfLines=1 时它不起作用

我必须在最后添加这一行以使其适用于所有情况..

label.width = min(label.width, 100)

于 2015-04-29T22:43:55.490 回答
-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]; 

希望它可以帮助你。

于 2013-05-06T13:42:24.713 回答