3

I have a UIButton object that has a title that's determined at runtime. The title might be multi-line, so I want to increase the UIButton object's height to match its title label's height. I do not want to create a UIButton subclass, as I've read that it is not good behavior. Which is why I don't understand why the answers from this question (which would otherwise solve this issue) all involve subclassing UIButton. This answer also involves subclassing UIButton as well.

I'm using auto-layout on 10.x and sizeToFit doesn't seem to do anything. I've also tried calling invalidateIntrinsicContentSize and that also doesn't do anything. I've sent content hugging to 1 and content compression to 999 and that also doesn't work.

Has Apple provided any official solution for automatically resizing a UIButton's height based on its title label? All of the similar questions linked to this one give different solutions, and a lot of them involve things that seem hacky (subclassing UIButton, adding a height constraint for the button to be updated when the title changes, manually re-setting the frame of the button).

Community
  • 1
  • 1
Apophenia Overload
  • 2,485
  • 3
  • 28
  • 46

3 Answers3

1

Solution using Autolayout

  1. UIButton object's height constraint should be a Greater Than or Equal relation.

  2. [objBtn sizeToFit];

KKRocks
  • 8,222
  • 1
  • 18
  • 84
1

Drag and drop one button in your interfacebuilder. Set four constraints like, 'top,leading,fixed width and fixed height`.

Then select fixed height constraint - > edit -> then change relationship = to >=.

Take outlet of your Button and in your viewDidload,

self.yourBtn.titleLabel.numberOfLines = 0;
[self.yourBtn setTitle:@"This is long title" forState:UIControlStateNormal];

That's it!!

It will increase height of your button as per it's title. Likewise you can make dynamic width also!

:)

Ketan Parmar
  • 27,092
  • 9
  • 50
  • 75
0

Set the line break mode to word wrap..

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
Bilal
  • 18,478
  • 8
  • 57
  • 72