How to align UILabel text from bottom?
How the UILabel
can be aligned from bottom. Let say, my label can hold three line of text.If the input text is single line, then this line should come bottom of the label.Please refer the below image for better understanding. The orange area is the full frame of label.Currently it has one line and it is aligned center. So what I want is, it should always aligned bottom regardless of how many lines.
Please suggest your ideas.
Thank you.
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};
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
我只对IB中的超级视图设置了一个底部约束,这对我而言无需使用代码,而且对于最大约束来说也是线数。
链接地址: http://www.djcxy.com/p/28188.html上一篇: 对齐UILabel中不同大小的文本
下一篇: 如何从底部对齐UILabel文本?