我使用以下代码自动调整 UITableView 中标签的高度。它在大多数情况下都有效,但有时文本会被切断。我的代码有问题吗,或者我需要添加其他内容吗? (代码基于this answer)
UILabel *textLabel = ((UILabel *)[cell viewWithTag:3]);
textLabel.text = text;
CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);
CGSize expectedLabelSize = [text sizeWithFont:textLabel.font constrainedToSize:maximumLabelSize lineBreakMode:textLabel.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = textLabel.frame;
newFrame.size.height = expectedLabelSize.height;
textLabel.frame = newFrame;
最佳答案
在 iOS 7 中 sizeWithFont: constrainedToSize: lineBreakMode:
已弃用,现在您应该使用:
CGSize maxSize = CGSizeMake(296.f, FLT_MAX);
CGRect labRect = [someText boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:textLabel.font} context:nil];
textLabel.frame = CGRectMake(0, 0, maxSize.width, labRect.size.height);
textLabel.text = someText;
关于iOS自动调整标签高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20618275/