1. sizeThatFits
let size = label.sizeThatFits(CGSizeMake(limitW, CGFloat(MAXFLOAT)))
2.通过 NSString 的 sizeWithAttributes 方法计算
let priceStr = NSString.init(format:"¥ %@",goodsModel.price_disct)
let attributes = [NSFontAttributeName:UIFont.systemFontOfSize(14)]
let size = priceStr.sizeWithAttributes(attributes)
3. boundingRect
let priceStr :String = ""
let attributes = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14)]
let size = priceStr.boundingRect(with: CGSize.init(width: CGFloat(MAXFLOAT), height: 30), options: .usesLineFragmentOrigin, attributes: attributes, context: nil).size
补充
1.如果是UITextView 还有内边距会造成计算错误
messageTextView?.textContainer.lineFragmentPadding = 0.0
messageTextView?.textContainerInset = UIEdgeInsets.zero
网友评论