2021 swfit 重拾之路

swift - 计算宽高

2021-07-07  本文已影响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
上一篇 下一篇

猜你喜欢

热点阅读