Wednesday, August 24, 2011

How to do vertical alignment for UILabels

I wrote something about that but I don't remember where :). Anyway, the easiest way is to add a method to the UILabel class.

Include in your file (or create a new one) this interface to extend the current UILabel one:
@interface UILabel (VerticalAlign)
- (void)alignTop;
@end
Add the method code in the .m file:
- (void)alignTop {
    CGSize fontSize = [self.text sizeWithFont:self.font];
    double finalHeight = fontSize.height * self.numberOfLines;
    double finalWidth = self.frame.size.width;    
    CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
    int newLinesToPad =
(finalHeight  - theStringSize.height) / fontSize.height;
    for(int i=0; i
        self.text = [self.text stringByAppendingString:@"\n "];
}

Done, now you can use this new method
[YourUILabel alignTop];

Hope help!

No comments:

Post a Comment

Post a Comment