[英]How to subclass a UILabel in swift with letter spacing set to 1.5 using NSKernAttribute
我試圖對UILabel進行子類化,以便將其默認字距設置為1.5,然后在我的應用程序中將其與多個標簽一起使用。 目標是將默認字距設置為開箱即用,這樣我就可以避免在各處重復編寫代碼,同時將標簽設置為屬性文本和常規文本的混合示例:
@IBoutlet weak var myLabel: CustomeLabelWithKern!
myLabel.attributedText = myAttributedText
@IBOutlet weak var myOtherLabelInADifferentViewController: CustomeLabelWithKern!
myOtherLabelInADifferentViewController.text "Foo Bar"
這兩個標簽的核數均應為1.5
這是我到目前為止所擁有的
class CustomLabel: UILabel {
var kerning: CGFloat = 1.5
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setKerning(kerning)
}
private func setKerning(kern: CGFloat) {
guard let text = self.text else { return }
let range = NSRange(location: 0, length: text.characters.count)
let mutableString = NSMutableAttributedString(attributedString: attributedText ?? NSAttributedString())
mutableString.addAttribute(NSKernAttributeName, value: kern, range: range)
attributedText = mutableString
}
}
到目前為止,這是我的想法,如果有人想出更好的解決方案,我現在將使用此解決方案,我也很樂意嘗試
class CustomLabel: UILabel {
static var kerning: CGFloat = 1.5
override func awakeFromNib() {
super.awakeFromNib()
setKerning(CustomLabel.kerning)
}
func setKerning(kern: CGFloat) {
let text = self.text ?? ""
let range = NSRange(location: 0, length: text.characters.count)
let mutableString = NSMutableAttributedString(attributedString: attributedText ?? NSAttributedString())
mutableString.addAttribute(NSKernAttributeName, value: kern, range: range)
attributedText = mutableString
}
}
我可以在viewController中這樣使用它
mylabel.text = "Hello World!" // this should be set to 1.5 by default but what if i am setting my label dynamically?
mylabel.setKerning(1.5) // Here i am passing the value so if the label is set dynamically set it will have correct spacing
// This also works if some of my labels have attributed text
myAttibutedLabel.attributedText = myAttributedText
myAttributedLabel.setKerning(1.5)
我認為這可以減少為UILabel類的擴展,就像這樣
extension UILabel {
func setKerning(kern: CGFloat) {
let text = self.text ?? ""
let range = NSRange(location: 0, length: text.characters.count)
let mutableString = NSMutableAttributedString(attributedString: attributedText ?? NSAttributedString())
mutableString.addAttribute(NSKernAttributeName, value: kern, range: range)
attributedText = mutableString
}
}
這樣子類化UILabel怎么樣:
class TestKerningLabel: UILabel {
func addKerning(kerningValue: Double) {
let attributedString = self.attributedText as! NSMutableAttributedString
attributedString.addAttribute(NSKernAttributeName, value: kerningValue, range: NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
}
}
然后在您的VC中使用它:
let testLabel = TestKerningLabel()
testLabel.attributedText = NSAttributedString(string: "test")
testLabel.addKerning(kerningValue: 1.5)
view.addSubview(testLabel)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.