文字底部+中心UILabel iOS Swift

时间:2015-12-03 06:31:09

标签: ios swift uilabel

我使用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有选项。但这不是我想要的。

请有人帮助我如何使我的文字中心+底部和中心+顶部

1 个答案:

答案 0 :(得分:5)

为了做到这一点,你应该覆盖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

如果您正在使用故事板,则使用此代码的最简单方法就是在故事板中更改标签类。