UIButton that resizes to fit its titleLabel

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

    Got same issue. It happens only if UIButton's titleLabel has more than one line. Is it a bug in UIKit?

    My Swift solution:

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

提交回复
热议问题