iOS: UIButton resize according to text length

后端 未结 14 846
你的背包
你的背包 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:14

    In Xcode 4.5 and above, this can now be done by using 'Auto-layouting / Constraints'.

    Major advantages are that:

    1. You don't need to programmatically set frames at all!
    2. If done right, you don't need to bother about resetting frames for orientation changes.
    3. Also, device changes needn't bother you (read, no need to code separately for different screen sizes).

    A few disadvantages:

    1. Not backward compatible - works only for iOS 6 and above.
    2. Need to get familiarised (but will save time later on).

    Coolest thing is we get to focus on declaring an intent such as:

    • I want these two buttons to be of the same width; or
    • I need this view to be vertically centered and extend to a max entent of 10 pts from the superview's edge; or even,
    • I want this button/label to resize according to the label it is displaying!

    Here is a simple tutorial to get introduced to auto-layouting.

    For a more details.

    It takes some time at first, but it sure looks like it will be well worth the effort.

提交回复
热议问题