iOS: UIButton resize according to text length
In interface builder, holding Command + = will resize a button to fit its text. I was wondering if this was possible to do programmatically before the button was added to the view.
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button.titleLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:12]];
[button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
// I need to know the width needed to accomodate NSStringVariable
[button setTitle:NSStringVariable forState:UIControlStateNormal];
// So that I can set the width property of the button before addSubview
[button setFrame:CGRectMake(10, 0, width, fixedHeight)];
[subNavigation addSubview:button];
In UIKit, there are additions to the NSString class to get from a given NSString object the size it'll take up when rendered in a certain font.
Docs was here. Now it's here under Deprecated.
In short, if you go:
CGSize stringsize = [myString sizeWithFont:[UIFont systemFontOfSize:14]];
//or whatever font you're using
[button setFrame:CGRectMake(10,0,stringsize.width, stringsize.height)];
...you'll have set the button's frame to the height and width of the string you're rendering.
You'll probably want to experiment with some buffer space around that CGSize, but you'll be starting in the right place.
The way to do this in code is:
[button sizeToFit];
If you are subclassing and want to add extra rules you can override:
- (CGSize)sizeThatFits:(CGSize)size;