iOS: UIButton resize according to text length

后端 未结 14 849
你的背包
你的背包 2020-11-29 17:28

In interface builder, holding Command + = will resize a button to fit its text. I was wondering if this was possible to do programmatically before the

14条回答
  •  执念已碎
    2020-11-29 18:24

    Swift 4.2

    Thank god, this solved. After setting a text to the button, you can retrieve intrinsicContentSize which is the natural size from an UIView (the official document is here). For UIButton, you can use it like below.

    button.intrinsicContentSize.width
    

    For your information, I adjusted the width to make it look properly.

    button.frame = CGRect(fx: xOffset, y: 0.0, width: button.intrinsicContentSize.width + 18, height: 40)
    

    Simulator

    UIButtons with intrinsicContentSize

    Source: https://riptutorial.com/ios/example/16418/get-uibutton-s-size-strictly-based-on-its-text-and-font

提交回复
热议问题