Matt Spoon
Matt Spoon

Reputation: 2830

How to change the vertical align of text in a UILabel (iOS8)

I'm making an app in which I need the text in a very large UILabel to appear at the bottom of the bounds of the label. Is there anyway to do this?

Through code or storyboards is fine.

Upvotes: 2

Views: 4913

Answers (4)

Dan Rosenstark
Dan Rosenstark

Reputation: 69747

For Swift 3 here's a top align

@objc(TopAlignLabel)
class TopAlignLabel: UILabel {

    override func drawText(in rect: CGRect) {
        var targetRect = textRect(forBounds: rect, limitedToNumberOfLines: numberOfLines)
        targetRect.origin.y = 0
        super.drawText(in: targetRect)
    }
}

for bottom align use rect.size.height - targetRect.size.height instead.

Upvotes: 3

夜一林风
夜一林风

Reputation: 1327

If subclassing is suitable for you, you can subclass UILabel and override the |drawTextInRect:| method to adjust the drawing area(CGRect) before actually drawing the text

- (void)drawTextInRect:(CGRect)rect{
    CGRect targetRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];
    targetRect.origin.y = rect.size.height - targetRect.size.height;
    [super drawTextInRect:targetRect];
}

Upvotes: 1

Duyen-Hoa
Duyen-Hoa

Reputation: 15784

Officially, we don't have api to change the vertical align of a UILabel's text. However, we can adjust the frame of your UILabel (as described in this post), or we can use some private API like this (not recommended)

Upvotes: 0

Mundi
Mundi

Reputation: 80265

With auto layout this is quite easy to do.

  1. Put the label into a container UIView.
  2. Set the constraints so it touches the sides and is fixed to the bottom.
  3. Leave the height variable, based on the content.

Upvotes: 5

Related Questions