UIButton that resizes to fit its titleLabel

前端 未结 12 1398
既然无缘
既然无缘 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:47

    Swift 4.x version of Kubba's answer:

    Need to Update Line Break as Clip/WordWrap/ in Interface builder to corresponding buttons.

    class ResizableButton: UIButton {
        override var intrinsicContentSize: CGSize {
           let labelSize = titleLabel?.sizeThatFits(CGSize(width: frame.width, height: .greatestFiniteMagnitude)) ?? .zero
           let desiredButtonSize = CGSize(width: labelSize.width + titleEdgeInsets.left + titleEdgeInsets.right, height: labelSize.height + titleEdgeInsets.top + titleEdgeInsets.bottom)
    
           return desiredButtonSize
        }
    }
    

提交回复
热议问题