UILabel - auto-size label to fit text?
Using [label sizeToFit];
will achieve the same result from Daniels Category.
Although I recommend to use autolayout and let the label resize itself based on constraints.
Please check out my gist where I have made a category for UILabel
for something very similar, my category lets a UILabel
stretch it's height to show all the content: https://gist.github.com/1005520
Or check out this post: https://stackoverflow.com/a/7242981/662605
This would stretch the height, but you can change it around easily to work the other way and stretch the width with something like this, which is I believe what you want to do:
@implementation UILabel (dynamicSizeMeWidth)
- (void)resizeToStretch{
float width = [self expectedWidth];
CGRect newFrame = [self frame];
newFrame.size.width = width;
[self setFrame:newFrame];
}
- (float)expectedWidth{
[self setNumberOfLines:1];
CGSize maximumLabelSize = CGSizeMake(CGRectGetWidth(self.bounds), CGFLOAT_MAX);
CGSize expectedLabelSize = [[self text] sizeWithFont:[self font]
constrainedToSize:maximumLabelSize
lineBreakMode:[self lineBreakMode]];
return expectedLabelSize.width;
}
@end
You could more simply use the sizeToFit
method available from the UIView
class, but set the number of lines to 1 to be safe.
iOS 6 update
If you are using AutoLayout, then you have a built in solution. By setting the number of lines to 0, the framework will resize your label appropriately (adding more height) to fit your text.
iOS 8 update
sizeWithFont:
is deprecated so use sizeWithAttributes:
instead:
- (float)expectedWidth{
[self setNumberOfLines:1];
CGSize expectedLabelSize = [[self text] sizeWithAttributes:@{NSFontAttributeName:self.font}];
return expectedLabelSize.width;
}
If we want that UILabel
should shrink and expand based on text size then storyboard with autolayout is best option. Below are the steps to achieve this
Steps
Put UILabel in view controller and place it wherever you want. Also put
0
fornumberOfLines
property ofUILabel
.Give it Top, Leading and Trailing space pin constraint.
- Now it will give warning, Click on the yellow arrow.
- Click on
Update Frame
and click onFix Misplacement
. Now this UILabel will shrink if text is less and expand if text is more.