Consider I have the following text in a UILabel
(a long line of dynamic text):
Since the alien army vastly outnumbers the team, players m
Here is a category version:
UILabel+AutoSize.h #import
@interface UILabel (AutoSize)
- (void) autosizeForWidth: (int) width;
@end
UILabel+AutoSize.m
#import "UILabel+AutoSize.h"
@implementation UILabel (AutoSize)
- (void) autosizeForWidth: (int) width {
self.lineBreakMode = UILineBreakModeWordWrap;
self.numberOfLines = 0;
CGSize maximumLabelSize = CGSizeMake(width, FLT_MAX);
CGSize expectedLabelSize = [self.text sizeWithFont:self.font constrainedToSize:maximumLabelSize lineBreakMode:self.lineBreakMode];
CGRect newFrame = self.frame;
newFrame.size.height = expectedLabelSize.height;
self.frame = newFrame;
}
@end