1

I have a problem with creating a button that will grows vertically according to length of the text set as its title. I have seen similar problem but that solution won't work in this case. When I set:

 label.numberOfLines = 0

then there is possibility to show multiline text but that doesn't affect button height itself. Has anyone faced that problem and found out nice and generic solution. I would love to avoid hardcoding some values for button's intrinsic size etc.

Community
  • 1
  • 1
Julian
  • 9,299
  • 5
  • 48
  • 65

3 Answers3

2

I ran into this myself and solved it by adding a height constraint to the button and overriding updateViewConstraints. Kind of hacky.

- (void)updateViewConstraints
{
    self.myButtonHeightConstraint.constant = self.myButton.titleLabel.frame.size.height;
    [super updateViewConstraints];
}

I also filed a bug with Apple about the UIButton not resizing to fit it's UIButtonLabel.


2017 version of code:

override func updateConstraints() {

    let h = titleLabel!.frame.size.height
    self.heightAnchor.constraint(equalToConstant: h).isActive = true
    super.updateConstraints()
}
Fattie
  • 27,874
  • 70
  • 431
  • 719
Fozzle
  • 573
  • 1
  • 6
  • 18
  • overriding `updateViewConstraints` is not hacky, I do not think that it is an apple bug but their intention I suppose (why?) – Julian Apr 13 '15 at 19:56
  • 1
    I feel like it's reasonable to expect the UIButton to expand along with it's label. For what it's worth they marked it as duplicate and the bug they referenced is still open, so it would appear to be a valid bug. – Fozzle Apr 13 '15 at 21:49
1

I have solved the issue by creating my own button, adding a label and setting constraints in the way that label's size determines the size of the button.

Julian
  • 9,299
  • 5
  • 48
  • 65
  • The problem with this is you don't get the default selection/deselection effect on the text then that is inherent with UIButtons. – Eric33187 Apr 16 '21 at 17:38
1

I see that is similar problem to this UIButton that resizes to fit its titleLabel

I had the same problem with UIButton with multilined text, and it also had an image. I used sizeThatFits: to calculate the size but it calculated wrong height.

I did not make it UIButtonTypeCustom, instead of that I called sizeThatFits: on button's titleLabel with size with smaller width (due to image in button):

CGSize buttonSize = [button sizeThatFits:CGSizeMake(maxWidth, maxHeight)];
CGSize labelSize = [button.titleLabel sizeThatFits:CGSizeMake(maxWidth - offset, maxHeight)]; // offset for image
buttonSize.height = labelSize.height;
buttonFrame.size = buttonSize;

And then I used height from that size to set button's frame correctly, and it WORKED :)

Maybe they have some bug in internal sizing of UIButton.

Community
  • 1
  • 1
BSevo
  • 743
  • 5
  • 13