How do I resize a UIButton to fit the text without it going wider than the screen?

Make sure you set the text on your button this way:

[myButton setTitle:@"my title" forState:UIControlStateNormal];

... and [myButton sizeToFit] should work like a charm.


[button sizeToFit] didn't work for me, but I've found a way using IB alone (xcode 4.5):

  1. Click on the UIButton
  2. in the Size inspector drag content hugging to 1 (both horizontal and vertical)
  3. drag compression resistance to 1000 (for both)
  4. under the UIButton's constraints click on Width and change priority to 250
  5. Do the same for Height
  6. You can use the UIButton's inset to control padding for left/right/top/bottom

You may want to look at the UIKit Additions to NSString documentation which includes methods for font measurement constrained to a specific width or box size.

When you set the button's title, you could measure the string using the sizeWithFont:forWidth:lineBreakMode: method, for example, and update your button's frame based on the size returned (possibly allowing for some padding around the edges).

Sorry I don't have a specific example for you.