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):
- Click on the
UIButton
- in the Size inspector drag
content hugging
to 1 (both horizontal and vertical) - drag
compression resistance
to 1000 (for both) - under the UIButton's
constraints
click onWidth
and changepriority
to 250 - Do the same for Height
- You can use the
UIButton
'sinset
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.