UIButton that resizes to fit its titleLabel

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

    I had to invalidate the intrinsic content size when the views were laid out and then calculate the height of the button for the intrinsicContentSize property.

    Here's the code in Swift3/Xcode 9

    override func layoutSubviews() {
        self.invalidateIntrinsicContentSize()
        super.layoutSubviews()
    }
    
    
    override var intrinsicContentSize: CGSize {
        return CGSize(width: self.frame.size.width, height: titleLabel!.frame.size.height + contentEdgeInsets.top + contentEdgeInsets.bottom)
    }
    

提交回复
热议问题