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)];
In XCode 4.5 and above, this can now be done by using 'Auto-layouting / Constraints'.
Major advantages are that:
A few disadvantages:
Coolest thing is we get to focus on declaring an intent such as:
Here is a simple tutorial to get introduced to auto-layouting.
For a more details.
It takes some time at first, but it sure looks like it will be well worth the effort.