Reputation: 9337
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.
Upvotes: 1
Views: 1689
Reputation: 593
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()
}
Upvotes: 2
Reputation: 793
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
.
Upvotes: 1
Reputation: 9337
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.
Upvotes: 1