如何从底部对齐UILabel文本?

NSU*_*ult 34 iphone alignment uilabel ios

如何UILabel从底部对齐.比方说,我的标签可以容纳三行文字.如果输入文字是单行,那么这行应该在标签的底部.请参考下面的图片以便更好地理解.橙色区域是标签的完整框架.目前它有一条线,它对齐中心.所以我想要的是,不管有多少行,它都应该始终对齐.

在此输入图像描述

请提出您的想法.

谢谢.

Par*_*shi 22

这有两种方法......

1.首先设置numberOfLines为0然后使用sizeToFit属性,UILabel这样你的UILabel显示器就可以了contentSize.

yourLabel.numberOfLines = 0;

[yourLabel sizeToFit];
Run Code Online (Sandbox Code Playgroud)

请参阅此链接中的更多信息:垂直对齐UILabel中的文本

2,另一种选择是采取UITextField替代的UILabel,并设置userInteractionEnabledNO下面喜欢...

[yourTextField setUserInteractionEnabled:NO];
Run Code Online (Sandbox Code Playgroud)

然后将contentVerticalAlignment属性设置为底部,如下所示....

[yourTextField setContentVerticalAlignment:UIControlContentVerticalAlignmentBottom];
Run Code Online (Sandbox Code Playgroud)

UPDATE

另外,有了UITextField,我们无法实现多条线路.因此,相反,我们可以使用UITextView并设置其userInteractionEnabledNO.然后,使用下面的代码使其底部对齐.

CGFloat topCorrect = ([label bounds].size.height - [label contentSize].height);
topCorrect = (topCorrect <0.0 ? 0.0 : topCorrect);
label.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
Run Code Online (Sandbox Code Playgroud)


Dus*_*tin 19

子类UILabel

@interface Label : UILabel

@end
Run Code Online (Sandbox Code Playgroud)

然后像这样覆盖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
Run Code Online (Sandbox Code Playgroud)


Dun*_*bar 13

使用contentMode属性设置顶部和底部的Swift 4.2版本:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后设置你的标签:

let label: VerticalAlignedLabel = UILabel()
label.contentMode = .bottom
Run Code Online (Sandbox Code Playgroud)