我有以下子类,并希望添加功能以轻松更改行高、字符间距等。这需要使用 NSAttributedString 类来完成,但是每当我使用段落样式设置标签的属性文本时,文本插入在标签在顶部和底部被忽略。此实现在没有段落样式或“文本”属性的情况下工作......
class Label: UILabel {
override var text: String? {
get {
return super.attributedText?.string
}
set {
self.updateText(newValue)
}
}
public var textInsets: UIEdgeInsets = .zero {
didSet {
self.invalidateIntrinsicContentSize()
}
}
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
let insetRect = bounds.inset(by: textInsets)
let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
return textRect.inset(by: textInsets.invert())
}
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: textInsets))
}
private func updateText(_ text: String?) {
// Setting attributed text here...
}
}
我在具有自动高度的 UIStackView 中有标签。我可以看到标签周围有填充,但文本没有居中......每当我使用段落样式时。我需要我相信的行高倍数的段落样式。
任何帮助将非常感激!