I have several UIButton
's together, and I want to adjust the font size so that it fits. However, each button should use the same font size so that they look the same. In other words, what I would like to do is set all button to the same minimum size.
_button1.titleLabel.adjustsFontSizeToFitWidth = YES;
_button2.titleLabel.adjustsFontSizeToFitWidth = YES;
float minFont1 = _button1.titleLabel.font.pointSize;
float minFont2 = _button2.titleLabel.font.pointSize;
float fontSize = MIN(minFont1, minFont2);
UIFont *tailoredFont = [_button1.titleLabel.font fontWithSize:fontSize];
_button1.titleLabel.font = tailoredFont;
_button2.titleLabel.font = tailoredFont;
However, this does not work because the titleLabel.font does not reflect the true size of the font.
The approach I ended up taking is to figure out the ideal font size for each button, and then setting all of the buttons to the smallest of the sizes.
- (float)idealFontSizeForButton:(UIButton *)button
{
UILabel *label = button.titleLabel;
float width = button.bounds.size.width - 10;
assert(button.bounds.size.width >= label.bounds.size.width);
CGFloat actualFontSize;
[label.text sizeWithFont:label.font
minFontSize:label.minimumFontSize
actualFontSize:&actualFontSize
forWidth:width
lineBreakMode:label.lineBreakMode];
debug(@"idealFontSizeForButton %f", actualFontSize);
return actualFontSize;
}
....
// Set text and make sure both buttons have the same font size
[_button1 setTitle:title1 forState:UIControlStateNormal];
[_button2 setTitle:title2 forState:UIControlStateNormal];
float minFont1 = [self idealFontSizeForButton:_button1];
float minFont2 = [self idealFontSizeForButton:_button2];
float fontSize = MIN(minFont1, minFont2);
UIFont *tailoredFont = [_button1.titleLabel.font fontWithSize:fontSize];
_button1.titleLabel.font = tailoredFont;
_button2.titleLabel.font = tailoredFont;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.