gpt4 book ai didi

ios - UIlabel中的字符串如何对齐?

转载 作者:行者123 更新时间:2023-11-29 00:12:50 26 4
gpt4 key购买 nike

有一个标签,它的宽度是 100,还有一些字符串,比如'ABC','ABCD','ABCDE'。我需要标签显示像'A B C','A B C D'这样的字符串, 'ABCDE'。该怎么做?

最佳答案

您可以使用 NSAttributedStringNSKernAttributeName 作为字母间距。我为您的目的创建了一个简单的子类:

class StretchingLabel: UILabel {

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

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

private func sharedInit() {
self.lineBreakMode = .byClipping
self.textAlignment = .center
}

override func awakeFromNib() {
super.awakeFromNib()
realignText()
}

private var scale: CGFloat { return UIScreen.main.scale }

override var text: String? {
didSet {
realignText()
}
}

private func realignText() {
guard let text = text else { return }

let textWidth = ceil((text as NSString).boundingRect(with: self.frame.size, options: [], attributes: [NSFontAttributeName: self.font], context: nil).width * scale) / scale
let availableWidth = self.frame.width - textWidth
let interLetterSpacing = availableWidth / CGFloat(text.characters.count - 1)

let attributedText = NSAttributedString(string: text, attributes: [NSFontAttributeName: self.font, NSKernAttributeName: interLetterSpacing])
self.attributedText = attributedText
}

}

关于ios - UIlabel中的字符串如何对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45940096/

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