用NSStringDrawingOptions计算label的高度
先来看OC
//字体大小配置
NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:fontSize]};
//计算size
CGSize size = [text boundingRectWithSize:CGSizeMake(width, 0) options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesDeviceMetrics attributes:attribute context:nil].size;
//label
高度
CGFloat height = size.height;
再来看Swift
//先将
String
类型转成NSString
类型
let text = str as NSString
//字体大小配置
let attribute = [kCTFontAttributeName: UIFont.systemFont(ofSize: fontsize)]
//计算size
let size = tempStr.boundingRect(with: CGSize.init(width: width, height: 0), options: NSStringDrawingOptions(rawValue: NSStringDrawingOptions.RawValue(UInt8(NSStringDrawingOptions.usesFontLeading.rawValue) | UInt8(NSStringDrawingOptions.usesDeviceMetrics.rawValue) | UInt8(NSStringDrawingOptions.usesLineFragmentOrigin.rawValue))), attributes: attribute as [NSAttributedStringKey : Any], context: nil).size
//label
高度
let height = size.height