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
Simply:
UIView
as wrapper with auto layout to views around. UILabel
inside that wrapper. Add constraints that will stick tyour label to edges of wrapper.UIButton
inside your wrapper, then simple add the same constraints as you did for UILabel
.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.
If you want to resize the text as opposed to the button, you can use ...
button.titleLabel.adjustsFontSizeToFitWidth = YES;
button.titleLabel.minimumScaleFactor = .5;
// The .5 value means that I will let it go down to half the original font size
// before the texts gets truncated
// note, if using anything pre ios6, you would use I think
button.titleLabel.minimumFontSize = 8;
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.
sizeToFit doesn't work correctly. instead:
myButton.size = myButton.sizeThatFits(CGSize.zero)
you also can add contentInset
to the button:
myButton.contentEdgeInsets = UIEdgeInsetsMake(8, 8, 4, 8)
Swift 4.2
Thank god, this solved. After setting a text to the button, you can retrieve intrinsicContentSize which is the natural size from an UIView (the official document is here). For UIButton, you can use it like below.
button.intrinsicContentSize.width
For your information, I adjusted the width to make it look properly.
button.frame = CGRect(fx: xOffset, y: 0.0, width: button.intrinsicContentSize.width + 18, height: 40)
Simulator
UIButtons with intrinsicContentSize
Source: https://riptutorial.com/ios/example/16418/get-uibutton-s-size-strictly-based-on-its-text-and-font