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

时间:2015-02-19 11:35:50

标签: ios objective-c cocoa-touch autolayout uilabel

我在Question之前复制了同样的问题。 我已经尝试了给出的解决方案并且无法解决它,因为当我使用Autolayout时 sizetofit 无效。

first screenshot

预期显示如下。

second screenshot

17 个答案:

答案 0 :(得分:129)

修改

在我原来的回答中,我使用的是标签的段落样式。事实证明,对于多行标签而言,这实际上会阻止标签成为多行标签。结果我把它从计算中删除了。在Github

中详细了解相关信息

对于那些使用开源更熟悉的人,请务必查看TTTAttributedLabel,您可以将标签的文本对齐方式设置为TTTAttributedLabelVerticalAlignmentTop


诀窍是子类UILabel并覆盖drawTextInRect。然后强制在标签边界的原点绘制文本。

这是一个你现在可以使用的天真实现:

夫特

@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
    }
}

目标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

由于我使用了IBDesignable,您可以将此标签添加到故事板并观看它,这就是我的样子

enter image description here

答案 1 :(得分:38)

如果你没有限制使用固定大小的UILabel,而不是在UILabel中对齐文本,只需在给定标签上使用≥约束来改变它的大小。 < / p>

enter image description here

使用自动布局是最优雅的解决方案。不要忘记将 numberOfLines 设置为零。

答案 2 :(得分:32)

您可以使用UITextView代替UILabel:
取消选中&#34;滚动已启用&#34;
取消选中&#34;可编辑&#34;
取消选中&#34;可选&#34;
将背景颜色设置为ClearColor

答案 3 :(得分:8)

我遇到了同样的问题,这就是我解决它的方法。我刚刚在Attribute Inspector下为Label编辑了Baseline。将其设置为“对齐中心”。

Setting baseline to Align Centers

答案 4 :(得分:7)

相反,我将底部空间常数更改为优先级@ 250并解决了我的问题。我的标签高度常数为&lt; =常数

答案 5 :(得分:4)

你可以通过移除最小高度来实现。

如果您需要标签下面的其他高度的最小高度,那么您将使用基于标签内容调整大小但容量最小的容器视图。

答案 6 :(得分:1)

自动布局仅适用于控制器的边缘/尺寸,而不适用于控制器内容。因此,使用自动布局在第一行顶部显示标签文本不是一个好主意。 据我说,sizetofit是最好的选择。

答案 7 :(得分:1)

我使用了@Daniel Golasko的解决方案,每当UILabel中的文本长于UILabel可能包含的内容时,文本就会开始向下移动而不是保持对齐顶部。

我更改了这一行以确保文字正确对齐

    [super drawTextInRect:CGRectMake(0, 0, ceilf(CGRectGetWidth(self.frame)),MIN(ceilf(labelStringSize.height), self.frame.size.height))];

答案 8 :(得分:1)

我有一个类似的问题,其中有3个标签。中间标签的文本可能比其他两个标签长得多,因此其高度可能会变得更大。

像这样:

enter image description here

我将中间标签的底部空间约束设置为&gt; =底部标签。

enter image description here

这解决了我的问题。

答案 9 :(得分:1)

雨燕4

您应该继承UILabel并覆盖文本显示呈现。

class UITopAlignedLabel: UILabel {
    override func drawText(in rect: CGRect) {
        guard let string = text else {
            super.drawText(in: rect)
            return
        }

        let size = (string as NSString).boundingRect(
            with: CGSize(width: rect.width, height: .greatestFiniteMagnitude),
            options: [.usesLineFragmentOrigin],
            attributes: [.font: font],
            context: nil).size

        var rect = rect
        rect.size.height = size.height.rounded()
        super.drawText(in: rect)
    }
}

答案 10 :(得分:1)

对于标签高度不需要保持不变的情况,有一个简单的解决方案:将Label放在Stack View中。务必将前导和尾随常量添加到Stack View。以下是如何在故事板中执行此操作的屏幕截图:

enter image description here

答案 11 :(得分:0)

在“界面生成器”中,只需将高度<=一些值而不是=。这将使文本从顶部开始,并根据需要扩展高度。例如,我有一个标签,其高度与主视图的大小成比例。所以我的身高限制看起来像这样: Height Constraint

答案 12 :(得分:0)

使用,在我的课程中,您可以通过alignment来更改文本contentMode

  

支持的情况:.top,.bottom,.left,.right,.topLeft,.topRight,.bottomLeft,.bottomRight

Swift4

import Foundation
import UIKit

@IBDesignable
class UIAlignedLabel: UILabel {

    override func drawText(in rect: CGRect) {
        if let text = text as NSString? {
            func defaultRect(for maxSize: CGSize) -> CGRect {
                let size = text
                    .boundingRect(
                        with: maxSize,
                        options: NSStringDrawingOptions.usesLineFragmentOrigin,
                        attributes: [
                            NSAttributedStringKey.font: font
                        ],
                        context: nil
                    ).size
                let rect = CGRect(
                    origin: .zero,
                    size: CGSize(
                        width: min(frame.width, ceil(size.width)),
                        height: min(frame.height, ceil(size.height))
                    )
                )
                return rect

            }
            switch contentMode {
            case .top, .bottom, .left, .right, .topLeft, .topRight, .bottomLeft, .bottomRight:
                let maxSize = CGSize(width: frame.width, height: frame.height)
                var rect = defaultRect(for: maxSize)
                switch contentMode {
                    case .bottom, .bottomLeft, .bottomRight:
                        rect.origin.y = frame.height - rect.height
                    default: break
                }
                switch contentMode {
                    case .right, .topRight, .bottomRight:
                        rect.origin.x = frame.width - rect.width
                    default: break
                }
                super.drawText(in: rect)
            default:
                super.drawText(in: rect)
            }
        } else {
            super.drawText(in: rect)
        }
    }

}

答案 13 :(得分:0)

这是Daniel Galasko对Swift 3解决方案的改进(在这里你也可以在顶部设置没有偏移的最大行号):

import UIKit

@IBDesignable class TopAlignedLabel: UILabel {
    override func drawText(in rect: CGRect) {
        if let stringText = text {
            let stringTextAsNSString = stringText as NSString
            let labelString = stringTextAsNSString.boundingRect(with: CGSize(width: frame.width, height: .greatestFiniteMagnitude),
                    options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
            super.drawText(in: CGRect(x: 0, y: 0, width: frame.width, height: ceil(labelString.size.height) > frame.height ? frame.height : ceil(labelString.size.height)))
        } else {
            super.drawText(in: rect)
        }
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        layer.borderWidth = 1
        layer.borderColor = UIColor.black.cgColor
    }
}

答案 14 :(得分:0)

  @IBInspectable var alignTop: Bool = false

  func setAlignTop() {
    let text = self.text!
    let lines = text.characters.split(separator: "\n").count
    if lines < self.numberOfLines {
      var newLines = ""
      for _ in 0..<(self.numberOfLines - lines) {
        newLines = newLines.appending("\n ")
      }
      self.text! = text.appending(newLines)
    }
  }

  override var text: String? {
    didSet {
      if alignTop {
        self.setAlignTop()
      }
    }
  }

答案 15 :(得分:0)

对我来说,我没有设置高度限制,文本总是从标签的顶部开始增长。 此标签的限制是顶部,左侧,右侧。 顺便说一下,我的标签有固定的行号,所以不用担心高度。

答案 16 :(得分:0)

您可以尝试按下按钮[button setContentVerticalAlignment:UIControlContentVerticalAlignmentTop];

编辑:

如果您只想使用标签,可以试试这个:

https://stackoverflow.com/a/11278660/1223897