UILabel with fixed width and flexible height

iphone, objective-c, sdk

Solution

I like to subclass `UILabel` to do this for me.

AutosizingLabel.h

#import <UIKit/UIKit.h>


@interface AutosizingLabel : UILabel {
    double minHeight;
}

@property (nonatomic) double minHeight;

- (void)calculateSize;

@end    

AutosizingLabel.m

#define MIN_HEIGHT 10.0f

#import "AutosizingLabel.h"

@implementation AutosizingLabel

@synthesize minHeight;

- (id)init {
    if ([super init]) {
        self.minHeight = MIN_HEIGHT;
    }

    return self;
}

- (void)calculateSize {
    CGSize constraint = CGSizeMake(self.frame.size.width, 20000.0f);
    CGSize size = [self.text sizeWithFont:self.font constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];    

    [self setLineBreakMode:UILineBreakModeWordWrap];
    [self setAdjustsFontSizeToFitWidth:NO];
    [self setNumberOfLines:0];
    [self setFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, MAX(size.height, MIN_HEIGHT))];

}

- (void)setText:(NSString *)text {  
    [super setText:text];

    [self calculateSize];
}

- (void)setFont:(UIFont *)font {
    [super setFont:font];

    [self calculateSize];
}

@end

To use this, import/create the .h and .m files in your project. Then if you are creating your `UILabel` in code, it would look something like this:

#import "AutosizingLabel.h"

- (void)viewDidLoad {
    [super viewDidLoad];

    AutosizingLabel *label = [[AutosizingLabel alloc] init];
    label.text = @"Some text here";
    [self.view addSubview:label];
}

If you're using a XIB, you can select any UILabel and click on the Identity Inspector in the right sidebar to set it's class to `AutosizingLabel`. In either case, setting the `.text` property will auto update the size of the label.

Problem

I've got an UILabel in a Detail View Controller, so its content changes depending on the selected table row. I have a problem, I would set a fixed width for my UILabel and a dynamic height depending on the text. How can I do this? (I'm sorry for my mistakes, but I'm not English)

Original source