0
有一个标签,它的宽度是100,还有一些字符串,如'ABC','ABCD','ABCDE'。我需要标签显示字符串' AB C','ABC D','ABCDE'。该怎么办?如何对齐UIlabel中的字符串?
有一个标签,它的宽度是100,还有一些字符串,如'ABC','ABCD','ABCDE'。我需要标签显示字符串' AB C','ABC D','ABCDE'。该怎么办?如何对齐UIlabel中的字符串?
您可以使用NSAttributedString
和NSKernAttributeName
作为字母间距。我创建了供您使用简单的子类:
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
}
}
嗯,我使用对象-C进行开发,但是谢谢你看我的问题,我看了你的答案是有用的我issue.It是一个很好的理念。 –
然后,你应该在你的问题(或通过标签)在未来说明。 –