How to align UILabel text from bottom?
Here are two ways of doing that...
1. First set numberOfLines
to 0 and then use sizeToFit
property of UILabel
so your UILabel
display with its contentSize
.
yourLabel.numberOfLines = 0;[yourLabel sizeToFit];
See more information from this link: Vertically align text within a UILabel
2. Another option is to take UITextField
instead of UILabel
and set userInteractionEnabled
to NO
like below...
[yourTextField setUserInteractionEnabled:NO];
and then set the contentVerticalAlignment
property to bottom like below...
[yourTextField setContentVerticalAlignment:UIControlContentVerticalAlignmentBottom];
UPDATE
Also, with UITextField
, we can't achieve multiple lines. So instead we can use UITextView
and set its userInteractionEnabled
to NO
. Then, use the code below to make it bottom aligned.
CGFloat topCorrect = ([label bounds].size.height - [label contentSize].height);topCorrect = (topCorrect <0.0 ? 0.0 : topCorrect);label.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
Swift 4.2 version using the contentMode
property to set top and bottom:
class VerticalAlignedLabel: UILabel { override func drawText(in rect: CGRect) { var newRect = rect switch contentMode { case .top: newRect.size.height = sizeThatFits(rect.size).height case .bottom: let height = sizeThatFits(rect.size).height newRect.origin.y += rect.size.height - height newRect.size.height = height default: () } super.drawText(in: newRect) }}
Then setup your label like that:
let label = VerticalAlignedLabel()label.contentMode = .bottom
Subclass UILabel
@interface Label : UILabel@end
Then override drawTextInRect like so
@implementation Label- (void)drawTextInRect:(CGRect)rect{ if(alignment == top) { rect.size.height = [self sizeThatFits:rect.size].height; } if(alignment == bottom) { CGFloat height = [self sizeThatFits:rect.size].height; rect.origin.y += rect.size.height - height; rect.size.height = height; } [super drawTextInRect:rect];}@end