获取 UILabel 中的行数 iOS8

Get the number of lines in UILabel iOS8

我看到这个问题有很多已弃用的答案:

如何根据设置的文本计算 UILabel 中使用的行数?

我知道我需要将 UILabel 设置为具有可通过自动换行调整大小的边界。这样,我就可以检测到我的 UILabel 的高度,并为我的 UITableViewCell 的高度调整一个 NSLayoutConstraint。基本上我的问题简单明了是:

如何确定我的 UILabel 正在使用的行数(基于 descriptionLabel.text)或高度以调整我的 UITableView 的大小UITableViewCell 包含我的 UILabel.

目前我用过这个代码:

descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 30, 270, 65)];
descriptionLabel.textColor = [UIColor blackColor];
descriptionLabel.numberOfLines = 0;
descriptionLabel.adjustsFontSizeToFitWidth = YES;

尝试使用以下代码

NSAttributedString *attrStr = ... // your attributed string
CGFloat width = 300; // whatever your desired width is
CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(width, 10000) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
//rect is the height of UILABEL which u can used as height of label or table view row or etc

我用这段代码非常简单地解决了我的问题:

CGSize maxSize = CGSizeMake(290.0f, CGFLOAT_MAX);
CGSize requiredSize = [descriptionLabel sizeThatFits:maxSize];
[descriptionLabel setFrame:CGRectMake(15, 50, requiredSize.width, requiredSize.height)];
NSLog(@"THE HEIGHT OF THIS DESCRIPTIONLABEL IS: %f",cell.frame.size.height);