swift - 计算宽高

作者: 大也 | 来源:发表于2021-07-07 08:34 被阅读0次

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

相关文章

网友评论

    本文标题:swift - 计算宽高

    本文链接:https://www.haomeiwen.com/subject/xfebultx.html