我试图子类一个UILabel,使它有一个默认的字距设置为1.5然后我将在我的应用中使用它和多个标签。目标是有默认的kern设置开箱,这样我就可以避免重复的代码在所有的地方,标签也设置为属性和常规文本的混合例子:
@IBoutlet weak var myLabel: CustomeLabelWithKern!
myLabel.attributedText = myAttributedText
@IBOutlet weak var myOtherLabelInADifferentViewController: CustomeLabelWithKern!
myOtherLabelInADifferentViewController.text "Foo Bar"
这两个标签的kern都应该是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类Like so
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)