Sizing a UILabel to fit?

I had to do this enough that I extended UILabel to do it for me:

@interface UILabel (BPExtensions)
- (void)sizeToFitFixedWidth:(CGFloat)fixedWidth;
@end

@implementation UILabel (BPExtensions)


- (void)sizeToFitFixedWidth:(CGFloat)fixedWidth
{
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, fixedWidth, 0);
    self.lineBreakMode = NSLineBreakByWordWrapping;
    self.numberOfLines = 0;
    [self sizeToFit];
}
@end

then to have a label to have a variable multiline height but a fixed width just:

[myLabel sizeToFitFixedWidth:kSomeFixedWidth];

Leave a Comment