在 UILabel 中垂直对齐文本(注意:使用 AutoLayout)

Vertically align text within a UILabel (Note : Using AutoLayout)(在 UILabel 中垂直对齐文本(注意:使用 AutoLayout))
本文介绍了在 UILabel 中垂直对齐文本(注意:使用 AutoLayout)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在复制

中查看更多信息

对于那些更习惯于使用开源的人,请务必查看 TTTAttributedLabel,您可以在其中设置标签的文本对齐到 TTTAttributedLabelVerticalAlignmentTop


诀窍是继承 UILabel 并覆盖 drawTextInRect.然后强制在标签边界的原点绘制文本.

这是一个您现在可以使用的简单实现:

斯威夫特

@IBDesignable 类 TopAlignedLabel: UILabel {覆盖 func drawTextInRect(rect: CGRect) {如果让 stringText = text {让 stringTextAsNSString = stringText 作为 NSStringvar labelStringSize = stringTextAsNSString.boundingRectWithSize(CGSizeMake(CGRectGetWidth(self.frame), CGFloat.max),选项:NSStringDrawingOptions.UsesLineFragmentOrigin,属性:[NSFontAttributeName:字体],上下文:无).sizesuper.drawTextInRect(CGRectMake(0, 0, CGRectGetWidth(self.frame), ceil(labelStringSize.height)))} 别的 {super.drawTextInRect(rect)}}覆盖 func prepareForInterfaceBuilder() {super.prepareForInterfaceBuilder()layer.borderWidth = 1layer.borderColor = UIColor.blackColor().CGColor}}

斯威夫特 3

 @IBDesignable 类 TopAlignedLabel: UILabel {覆盖 func drawText(in rect: CGRect) {如果让 stringText = text {让 stringTextAsNSString = stringText 作为 NSString让 labelStringSize = stringTextAsNSString.boundingRect(with: CGSize(width: self.frame.width,height: CGFloat.greatestFiniteMagnitude),选项:NSStringDrawingOptions.usesLineFragmentOrigin,属性:[NSFontAttributeName:字体],上下文:无).sizesuper.drawText(in: CGRect(x:0,y: 0,width: self.frame.width, height:ceil(labelStringSize.height)))} 别的 {super.drawText(在:矩形)}}覆盖 func prepareForInterfaceBuilder() {super.prepareForInterfaceBuilder()layer.borderWidth = 1layer.borderColor = UIColor.black.cgColor}}

目标-C

IB_DESIGNABLE@interface TopAlignedLabel : UILabel@结尾@implementation TopAlignedLabel- (void)drawTextInRect:(CGRect)rect {如果(self.text){CGSize labelStringSize = [self.text boundingRectWithSize:CGSizeMake(CGRectGetWidth(self.frame), CGFLOAT_MAX)选项:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading属性:@{NSFontAttributeName:self.font}上下文:nil].size;[super drawTextInRect:CGRectMake(0, 0, ceilf(CGRectGetWidth(self.frame)),ceilf(labelStringSize.height))];} 别的 {[超级 drawTextInRect:rect];}}- (void)prepareForInterfaceBuilder {[超级prepareForInterfaceBuilder];self.layer.borderWidth = 1;self.layer.borderColor = [UIColor blackColor].CGColor;}@结尾


由于我使用了 IBDesignable,您可以将此标签添加到情节提要中并观看它的运行,这对我来说就是这样

I am Copying the same Question asked Before Question. I have tried the solutions given and was not able to solve it since sizetofit was not effective when I use Autolayout.

The expected display is like below.

解决方案

Edit

In my original answer I was using the paragraph style of the label. Turns out that for multi-line labels this actually prevents the label from being multi-line. As a result I removed it from the calculation. See more about this in Github

For those of you more comfortable with using Open Source definitely look at TTTAttributedLabel where you can set the label's text alignment to TTTAttributedLabelVerticalAlignmentTop


The trick is to subclass UILabel and override drawTextInRect. Then enforce that the text is drawn at the origin of the label's bounds.

Here's a naive implementation that you can use right now:

Swift

@IBDesignable class TopAlignedLabel: UILabel {
    override func drawTextInRect(rect: CGRect) {
        if let stringText = text {
            let stringTextAsNSString = stringText as NSString
            var labelStringSize = stringTextAsNSString.boundingRectWithSize(CGSizeMake(CGRectGetWidth(self.frame), CGFloat.max),
                options: NSStringDrawingOptions.UsesLineFragmentOrigin,
                attributes: [NSFontAttributeName: font],
                context: nil).size
            super.drawTextInRect(CGRectMake(0, 0, CGRectGetWidth(self.frame), ceil(labelStringSize.height)))
        } else {
            super.drawTextInRect(rect)
        }
    }
    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        layer.borderWidth = 1
        layer.borderColor = UIColor.blackColor().CGColor
    }
}

Swift 3

  @IBDesignable class TopAlignedLabel: UILabel {
    override func drawText(in rect: CGRect) {
        if let stringText = text {
            let stringTextAsNSString = stringText as NSString
            let labelStringSize = stringTextAsNSString.boundingRect(with: CGSize(width: self.frame.width,height: CGFloat.greatestFiniteMagnitude),
                                                                            options: NSStringDrawingOptions.usesLineFragmentOrigin,
                                                                            attributes: [NSFontAttributeName: font],
                                                                            context: nil).size
            super.drawText(in: CGRect(x:0,y: 0,width: self.frame.width, height:ceil(labelStringSize.height)))
        } else {
            super.drawText(in: rect)
        }
    }
    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        layer.borderWidth = 1
        layer.borderColor = UIColor.black.cgColor
    }
}

Objective-C

IB_DESIGNABLE
@interface TopAlignedLabel : UILabel

@end

@implementation TopAlignedLabel

- (void)drawTextInRect:(CGRect)rect {
    if (self.text) {
        CGSize labelStringSize = [self.text boundingRectWithSize:CGSizeMake(CGRectGetWidth(self.frame), CGFLOAT_MAX)
                                                         options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                                      attributes:@{NSFontAttributeName:self.font}
                                                         context:nil].size;
        [super drawTextInRect:CGRectMake(0, 0, ceilf(CGRectGetWidth(self.frame)),ceilf(labelStringSize.height))];
    } else {
        [super drawTextInRect:rect];
    }
}

- (void)prepareForInterfaceBuilder {
        [super prepareForInterfaceBuilder];
        self.layer.borderWidth = 1;
        self.layer.borderColor = [UIColor blackColor].CGColor;
}

@end


Since I used IBDesignable you can add this label to a storyboard and watch it go, this is what it looks like for me

这篇关于在 UILabel 中垂直对齐文本(注意:使用 AutoLayout)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
tabbar middle tab out of tabbar corner(选项卡栏中间的选项卡角外)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)
Get an event when UIBarButtonItem menu is displayed(显示UIBarButtonItem菜单时获取事件)