gpt4 book ai didi

ios - 文本底部 + 居中 UILabel iOS Swift

转载 作者:可可西里 更新时间:2023-11-01 00:23:19 25 4
gpt4 key购买 nike

我使用 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

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

关于ios - 文本底部 + 居中 UILabel iOS Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34059260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com