UIButton that resizes to fit its titleLabel

前端 未结 12 1400
既然无缘
既然无缘 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条回答
  •  猫巷女王i
    2020-12-01 09:29

    Override the -(CGSize)intrinsicContentSize in Custom UIButton as given below.

    Objective - C:

    -(CGSize)intrinsicContentSize {
        CGSize titleLabelIntrinsicSize = [self.titleLabel intrinsicContentSize];
        return CGSizeMake(titleLabelIntrinsicSize.width + self.contentEdgeInsets.left + self.contentEdgeInsets.right, titleLabelIntrinsicSize.height + self.contentEdgeInsets.top + self.contentEdgeInsets.bottom);
    }
    

    Swfit :

    override var intrinsicContentSize: CGSize {
            get {
                if let thisSize = self.titleLabel?.intrinsicContentSize {
                    return CGSize(width: thisSize.width + self.contentEdgeInsets.left + self.contentEdgeInsets.right, height: thisSize.height + self.contentEdgeInsets.top + self.contentEdgeInsets.bottom)
                }
                return super.intrinsicContentSize
            }
        }
    

提交回复
热议问题