UIButton that resizes to fit its titleLabel

前端 未结 12 1367
既然无缘
既然无缘 2020-12-01 09:13

I have a UIButton that I add to my view controller\'s view in a storyboard. I add centering constraints to position it and leading space constraints to limit it

12条回答
  •  离开以前
    2020-12-01 09:43

    class SFResizableButton: UIButton {
      override var intrinsicContentSize: CGSize {
        get {
          var labelSize = CGSize.zero
            if let text = titleLabel?.text, let font = titleLabel?.font {
              labelSize.width = text.width(constrained: .greatestFiniteMagnitude, font: font)
            } else if let att = titleLabel?.attributedText {
              labelSize.width = att.width(constrained: .greatestFiniteMagnitude)
            }
          if let imageView = imageView {
            labelSize.width = labelSize.width + imageView.frame.width
          }
          let desiredButtonSize = CGSize(width: ceil(labelSize.width) + titleEdgeInsets.left + titleEdgeInsets.right + imageEdgeInsets.left + imageEdgeInsets.right, height: labelSize.height + titleEdgeInsets.top + titleEdgeInsets.bottom + imageEdgeInsets.top + imageEdgeInsets.bottom)
    
            return desiredButtonSize
        }
      }
    }
    extesion String {
      func width(constrained height: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
          let boundingBox = (self as NSString).boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
    
          return boundingBox.width
      }
    }
    
    extension NSAttributedString {
      func width(constrained height: CGFloat) -> CGFloat {
        let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
          let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil)
    
          return boundingBox.width
      }
    }
    

提交回复
热议问题