文本底部 + 中心 UILabel iOS Swift

Text bottom + center UILabel iOS Swift

我使用 Swift 创建了一个 iOS 应用程序。现在我有一个问题,我想让我的文本在一个标签中居中+底部,在另一个标签中居中+顶部。可以吗?

我试过了

//Here learnItem is my label.
     let constraintSize: CGSize = CGSizeMake(learnItem.frame.size.width, CGFloat(MAXFLOAT))
     let textRect: CGRect = learnItem.text!.boundingRectWithSize(constraintSize, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: learnItem.font], context: nil)
            learnItem.drawRect(textRect);

没有任何影响。所以也许这是一个 wromg 代码。我也看到了

learnItem.textAlignment = .Center

center, justified, left, natural, right有选项。但这不是我想要的。

请有人帮我如何让我的文字居中+底部和居中+顶部?

为此,您应该覆盖 drawTextInRect 方法。

// MARK: - BottomAlignedLabel

@IBDesignable class BottomAlignedLabel: UILabel {

    // MARK: Lifecycle

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func drawText(in rect: CGRect) {

        guard text != nil else {
            return super.drawText(in: rect)
        }

        let height = self.sizeThatFits(rect.size).height
        let y = rect.origin.y + rect.height - height
        super.drawText(in: CGRect(x: 0, y: y, width: rect.width, height: height))
    }
}

对于顶部对齐 y 应该是 0

如果您使用的是情节提要,使用此代码的最简单方法就是更改情节提要中标签的 class。