我需要为UILabel
呈现的文本设置两个属性:字母(字距)之间的间距及其删除线样式。基于NSAttributedStringKey
文档,我为UILabel
创建了以下扩展名:
extension UILabel {
func setStrikeThroughSpacedText(text: String, kern: CGFloat?) {
var attributes: [NSAttributedStringKey : Any] = [:]
if let kern = kern {
attributes[.kern] = kern
}
attributes[.strikethroughStyle]
= NSNumber(integerLiteral: NSUnderlineStyle.styleSingle.rawValue)
self.attributedText = NSAttributedString(string: text,
attributes: attributes)
}
}
但是,似乎
.kern
key 与.strikethroughStyle
key 发生了某种冲突,因为如果我指定了kern,则将应用kern,而不是删除线样式。如果我未指定kern(因此扩展名不应用.kern
属性),则删除线样式有效。任何人都有不同的方法来解决此错误(我认为这是一个错误)?
最佳答案
试试这个,它应该对你有用
注意:我在中测试过Swift 4
let label = UILabel()
let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"
let attrString = NSMutableAttributedString(string: stringValue)
let style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: NSRange(location: 0, length: stringValue.count))
attrString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: 2, range: NSMakeRange(0, attrString.length))
attrString.addAttribute(NSAttributedStringKey.kern, value: 2, range: NSMakeRange(0, attrString.length))
label.attributedText = attrString
结果:
Sim 1:Strike + LineSpacing
Sim 2:罢工+行距+字符间距