Dec 312011
 

The UILabel is a great widget for displaying multi-line text, it isn’t just for single line entries. But how do you get it to word wrap and have the text at the upper left. Here’s a snippet I use all the time:

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

@implementation UILabel (EnkiExtensions)
- (void)sizeToFitFixedWidth:(CGFloat)fixedWidth
{
    if (fixedWidth < 0) {
        self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, 0);
    } else {
        self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, fixedWidth, 0);
    }
    self.lineBreakMode = UILineBreakModeWordWrap;
    self.numberOfLines = 0;
    [self sizeToFit];
}
@end

It is pretty straightforword to call with only one gotcha:

    helpLabel_.text = @"You need to cut the blue wire and ground the red wire. Do not cut the red wire and ground the blue wire, that would be bad.";
    [helpLabel_ sizeToFitFixedWidth: _helpFPO.frame.size.width ];

redwire

What’s the gotcha? Notice the helpPFO variable? When you design your UI in Interface Builder you placed your UILabel but you also want to place a UIView in the exact same spot. Hook it up to the variable helpFPO. Why not just use _helpLabel’s frame to set the width? If you did that it could shrink over time if the contents changed and you called sizeToFitFixedWidth again. FPO is an old page layout term, it means For Position Only.

Also notice that I’ve only adjusted the width, not the height.

This has been incorporated into the open source EnkiUtils.