iOS sizeToFit不显示文字

时间:2014-03-10 15:59:30

标签: ios cocoa-touch uilabel

我正在为Storyboard视图创建这些标签。我将autolayout设置为OFF并且我将numberoflines设置为0但是只有当我注释掉sizeToFit时才会显示文本。然后,当然,当文本的高度大于40时,文本会被切断。

- (void)viewDidLoad
{

[super viewDidLoad];
first = @"This text fits in the label";
second = @"This large text is too large for the label but because the words are normal sized, shows the more button correctly at the bottom right";
third = @"Doesn't show the more button correctly because WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW";

firstlbl = [[UILabel alloc]initWithFrame:CGRectMake(13, 57, 295, 40)];
secondlbl = [[UILabel alloc]initWithFrame:CGRectMake(13, 152, 295, 40)];
thirdlbl = [[UILabel alloc]initWithFrame:CGRectMake(13, 225, 295, 40)];

[firstlbl setFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:14]];
[secondlbl setFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:14]];
[thirdlbl setFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:14]];

firstlbl.lineBreakMode = NSLineBreakByWordWrapping;
secondlbl.lineBreakMode = NSLineBreakByWordWrapping;
thirdlbl.lineBreakMode = NSLineBreakByWordWrapping;

firstlbl.numberOfLines = 0;
secondlbl.numberOfLines = 0;
thirdlbl.numberOfLines = 0;
[firstlbl sizeToFit];
[secondlbl sizeToFit];
[thirdlbl sizeToFit];

[firstlbl setText:first];
[secondlbl setText:second];
[thirdlbl setText:third];

[self.view addSubview:firstlbl];
[self.view addSubview:secondlbl];
[self.view addSubview:thirdlbl];

}

1 个答案:

答案 0 :(得分:1)

在设置文字之前,您正在调用sizeToFit,因此它的大小调整为CGRectZero。切换这些电话,它会工作。

sizeToFit并不意味着“自动调整尺寸以适合您的内容”,这意味着“立即更新您的尺寸以适应您的内容”。对文本的后续更新不会更改框架。

如果您想要前一种行为,那么它会自动调整其内容的大小,自动布局可能是最简单的方法。