2

I have a UIButton where the height must be able to grow according to the title that the button is given (dynamically).

I've set the button's title label to have numberOfLines = 0, and set the LineBreakMode to Word Wrap. As a result, the button's text wraps as expected, but the button itself (I.E the tappable area) is not resized. See the following screenshot:

enter image description here

In this screenshot, the button's background colour is light gray to illustrate my point. As you can see, the button's title label (the blue text) is much larger than the background of the button. The button is constrained to be centred vertically and its leading/trailing anchors pinned to the superview so there is no constraint on it's height.

Am I missing a setting or trick that enables the button's area to grow relative to the title label?

Abhishek Jain
  • 4,557
  • 2
  • 32
  • 31
user1636130
  • 1,615
  • 5
  • 29
  • 47
  • set equal height constraint for button and label – Saurabh Jain Aug 16 '17 at 13:31
  • This is the UIButton's default title label, rather than a separate label that I've added myself. I would have thought that the button would intrinsically size to fit the label. – user1636130 Aug 16 '17 at 13:34
  • Create a custom class of UIButton and add set the intrinsic content size of button and add code, var intrinsicContentSize: CGSize { return CGSize(width: frame.size.width, height: titleLabel?.frame?.size?.height)! } – Saurabh Jain Aug 16 '17 at 13:42
  • Please try my code – Saurabh Jain Aug 16 '17 at 13:58
  • This post has an excellent solution - even shows how to use this as `@IBDesignable` so you can see the auto-sizing at design-time. I added an answer in that post with Swift 3 updates. – DonMag Aug 16 '17 at 14:00
  • @SaurabhJain, I wanted to avoid overriding the intrinsic content size of the button if possible. This seemed like something that a UIButton should be capable of without subclassing! – user1636130 Aug 16 '17 at 14:17
  • Whoops - I forgot to add the link: https://stackoverflow.com/questions/23845982/multiline-uibutton-and-autolayout/45715643#45715643 – DonMag Aug 16 '17 at 14:18

0 Answers0