2

Is there any way to programatically align UILabel text to the bottom of the frame?

How it should look like:

1 line of text:

 ____________
|            |
|            |
|            |
|            |
| some text1 |
 ____________


2 lines of text:

 ____________
|            |
|            |
|            |
| some text1 |
| some text2 |
 ____________
andrejbroncek
  • 421
  • 5
  • 17
  • 1
    Possible duplicate of [How to align UILabel text from bottom?](http://stackoverflow.com/questions/18247934/how-to-align-uilabel-text-from-bottom) – Leonardo Oct 14 '15 at 12:08

1 Answers1

0

You can extend UILabel Class as described in this answer:

#pragma mark VerticalAlign
@interface UILabel (VerticalAlign)
- (void)alignTop;
- (void)alignBottom;
@end


@implementation UILabel (VerticalAlign)
- (void)alignTop
{
    CGSize fontSize = [self.text sizeWithFont:self.font];

    double finalHeight = fontSize.height * self.numberOfLines;
    double finalWidth = self.frame.size.width;    //expected width of label


    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<= newLinesToPad; i++)
    {
        self.text = [self.text stringByAppendingString:@" \n"];
    }
}

- (void)alignBottom
{
    CGSize fontSize = [self.text sizeWithFont:self.font];

    double finalHeight = fontSize.height * self.numberOfLines;
    double finalWidth = self.frame.size.width;    //expected width of label


    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< newLinesToPad; i++)
    {
        self.text = [NSString stringWithFormat:@" \n%@",self.text];
    }
}
@end

and for alignment you just have to use:

[myLabel alignBottom];

EDIT:
As sizeWithFont deprecated you can try out this solution. I have not tested but you can go through it i=once. https://stackoverflow.com/a/22849805/4685283

Community
  • 1
  • 1
  • The problem is, `sizeWithFont` is deprecated. I don't really know what should I replace it with. – andrejbroncek Oct 14 '15 at 13:17
  • Documentation is pretty clear about that: Use [boundingRectWithSize:options:attributes:context:](https://developer.apple.com/library/ios/documentation/UIKit/Reference/NSString_UIKit_Additions/index.html#//apple_ref/occ/instm/NSString/boundingRectWithSize:options:attributes:context:). – mAu Jan 11 '16 at 11:12