I tried to fit UIButton to its title text by calling
[SizeToFit]. Unfortunately, I got unwanted result as the following.
I suppose that the button's size is smaller than its title size. therefore, the title string was abbreviated. The simple and silly solution I chose was plus 20pt to its width after calling
I believe that there is any solution better than I used.
Is there anybody who know it?
sizeToFit does not resize the text but it is used to resize the view so it encloses its subviews. Please use
adjustsFontSizeToFitWidth instead to resize font size to fit your button width.
btnMyButton.titleLabel.adjustsFontSizeToFitWidth = YES;
Or if you want to resize your button to fit the width of your font, here is how you can do that too:
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:btnMyButton.titleLabel.font, NSFontAttributeName, nil]; CGFloat buttonWidth = [[[NSAttributedString alloc] initWithString:btnMyButton.titleLabel.text attributes:attributes] size].width; CGRect frame = btnMyButton.frame; btnMyButton.frame = CGRectMake(frame.origin.x, frame.origin.y, buttonWidth, frame.size.width);
buttonWidth does give you the width your title requires to fit in, however if its still not working then please can you verify that:
1) Your button does not have any margins set, if it does then you might want to add those to your
buttonWidth variable before setting
buttonWidth += 10; //assuming you have 10pt margins.
2) Your button is not getting shrunk via an
AutoLayout constraint or
3) Your button is not getting font, size, or title set after
btnMyButton.frame has been set.
4) Your button has enough room to resize.