当我设置一个包含大量内容的UILabel时遇到问题,例如20,000个单词。我用这种方法计算UILabel的大小:
CGSize labelSize = [myLabel.text sizeWithFont:myLabel.text.font
constrainedToSize:CGSizeMake(400, CGFLOAT_MAX)
lineBreakMode:UILineBreakModeWordWrap];
显示标签时总会崩溃。
我不知道为什么,但我用UITextView替换它并解决了问题。
有谁知道这个的原因吗?谢谢!
答案 0 :(得分:0)
float desiredHeight = 50.0;
NSString *yourText = @\"This is some\nmultiline text\nthat you want to fit in your frame.\";
CGRect frame = CGRectMake(30.0, 30.0, 250.0, desiredHeight);
int originalFontSize = 30; // let's say
UILabel *label = [[UILabel alloc] initWithFrame:frame];
label.font = [UIFont boldSystemFontOfSize:originalFontSize];
frame.size.height = 3000.0; // just make sure it's big enough
CGSize result = [yourText sizeWithFont:label.font constrainedToSize:frame.size lineBreakMode:UILineBreakModeWordWrap];
int newFontSize = (desiredHeight / result.height) * (float)originalFontSize;
label.font = [UIFont boldSystemFontOfSize:newFontSize];
label.numberOfLines = 0;
label.text = yourText;
[self.view addSubview:label];
试试这个并调整字体。还调整行号。它可以纠正我希望的问题
答案 1 :(得分:0)
也许最好做这样的事情:
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(0.0, 0.0, self.view.frame.size.width, 0.0)];
[label setText: @"your text"];
[label sizeToFit];
CGRect labelFrame = label.frame;
labelFrame.size.height = label.contentSize.height;
label.frame = labelFrame;
[self.view addSubview: label];
现在您可以添加文字,其高度将按xcode计算