【问题标题】:How to change the vertical align of text in a UILabel (iOS8)如何更改 UILabel (iOS8) 中文本的垂直对齐方式
【发布时间】:2015-06-26 00:19:28
【问题描述】:

我正在制作一个应用程序,其中我需要一个非常大的 UILabel 中的文本出现在标签边界的底部。有没有办法做到这一点?

通过代码或故事板很好。

【问题讨论】:

    标签: ios swift labels text-alignment


    【解决方案1】:

    对于 Swift 3,这里是顶部对齐

    @objc(TopAlignLabel)
    class TopAlignLabel: UILabel {
    
        override func drawText(in rect: CGRect) {
            var targetRect = textRect(forBounds: rect, limitedToNumberOfLines: numberOfLines)
            targetRect.origin.y = 0
            super.drawText(in: targetRect)
        }
    }
    

    对于底部对齐,请改用rect.size.height - targetRect.size.height

    【讨论】:

      【解决方案2】:

      如果子类化适合你,你可以继承 UILabel 并覆盖 |drawTextInRect:|在实际绘制文本之前调整绘图区域(CGRect)的方法

      - (void)drawTextInRect:(CGRect)rect{
          CGRect targetRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];
          targetRect.origin.y = rect.size.height - targetRect.size.height;
          [super drawTextInRect:targetRect];
      }
      

      【讨论】:

        【解决方案3】:

        正式地,我们没有 api 来改变 UILabel 文本的垂直对齐方式。但是,我们可以调整你的 UILabel 的框架(如this post 中所述),或者我们可以使用一些私有 API like this(不推荐)

        【讨论】:

          【解决方案4】:

          使用自动布局,这很容易做到。

          1. 将标签放入容器UIView
          2. 设置约束,使其接触侧面并固定在底部。
          3. 根据内容保留高度变量。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-05-25
            • 2022-01-05
            • 1970-01-01
            • 2013-12-26
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多