如何从底部对齐UILabel
。比方说,我的标签可以容纳三行text.If,输入的文本是单行,那么这一行应该放在label.Please的底部,参考下面的图片,以便更好地理解。橙色区域是label.Currently的全部框架,它有一条线,它是对齐的中心。所以我想要的是,不管有多少行,它都应该对齐底部。
请提出你的想法。
谢谢。
发布于 2013-08-15 07:24:20
这里有两种方法..。
1.首先将numberOfLines
设置为0,然后使用UILabel
的sizeToFit
属性来显示UILabel
及其contentSize
。
yourLabel.numberOfLines = 0;
[yourLabel sizeToFit];
请参阅此链接中的更多信息:在UILabel中垂直对齐文本
2.的另一种选择是选择UITextField
而不是UILabel
,并将userInteractionEnabled
设置为NO
,如下所示.
[yourTextField setUserInteractionEnabled:NO];
然后将contentVerticalAlignment
属性设置为底部,如下所示。
[yourTextField setContentVerticalAlignment:UIControlContentVerticalAlignmentBottom];
更新
而且,使用UITextField
,我们不能实现多行。因此,我们可以使用UITextView
并将其userInteractionEnabled
设置为NO
。然后,使用下面的代码使其底部对齐。
CGFloat topCorrect = ([label bounds].size.height - [label contentSize].height);
topCorrect = (topCorrect <0.0 ? 0.0 : topCorrect);
label.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
发布于 2018-05-21 13:30:23
SWIFT4.2版本使用contentMode
属性设置顶部和底部:
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)
}
}
然后这样设置您的标签:
let label = VerticalAlignedLabel()
label.contentMode = .bottom
发布于 2014-04-03 21:58:51
子类UILabel
@interface Label : UILabel
@end
然后像这样覆盖drawTextInRect
@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
https://stackoverflow.com/questions/18247934
复制相似问题