Reputation: 2242
Button size is enough, however when I change title, the title text cannot fit the button width. Any SDK function can solve this problem, or I need to manually code to solve it?
Please refer to following pictures.
design in the nib file.
initial show in simulator
when I change the title text
_button.titleLabel.adjustsFontSizeToFitWidth = YES;
the way will change my font size. I cannot accept the way.
[_button setTitleEdgeInsets:UIEdgeInsetsMake(10.0, 10.0, 0.0,0.0)];
the way change label's position only, not label size.
[_button.titleLabel sizeToFit];
result is same with picture(3).
[_button sizeToFit];
title moved to upper left corner, and the title still the same result.
Just confused, my button size is big enough, why title size is so small?
Upvotes: 25
Views: 29620
Reputation: 1543
Use this.
Objective-c
button.titleLabel.numberOfLines = 1;
button.titleLabel.adjustsFontSizeToFitWidth = YES;
button.titleLabel.lineBreakMode = NSLineBreakByClipping;
Swift 2.0
button.titleLabel?.numberOfLines = 0
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
NOTE: Swift code courtesy: @Rachel Harvey
Swift 5.0
button.titleLabel?.numberOfLines = 0
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.lineBreakMode = .byWordWrapping
Upvotes: 44
Reputation: 39181
Here is the Swift version:
let button = UIButton()
button.titleLabel?.numberOfLines = 1
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.lineBreakMode = NSLineBreakMode.ByClipping
Upvotes: 2
Reputation: 2318
Make sure also that the label doesn't adjust later spacing, as that seems to take precedence over adjusting font size. Also make sure the minimumScaleFactor < 1.
button.titleLabel.adjustsFontSizeToFitWidth = YES;
button.titleLabel.adjustsLetterSpacingToFitWidth = NO;
button.titleLabel.minimumScaleFactor = 0.5;
Upvotes: 3
Reputation: 3274
For people who come across with this question:
Try using the setter:
[self.myButton setTitle:@"Title" forState:UIControlStateNormal];
[self.myButton sizeToFit];
Upvotes: 14
Reputation: 104082
In IB, just select the button, go to the editor menu, and choose "Size To Fit Content"
Upvotes: 0