我需要为UILabel
所呈现的文本设置两个属性:字母间的间距(kern)及其删除线样式。根据{{1}}文档,我创建了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
键冲突,因为如果我指定kern,则应用kern,但不应用删除线样式。如果我没有指定kern(因此扩展名不应用.strikethroughStyle
属性),则删除线样式有效。
任何人都有不同的方法来解决这个错误(我认为这是一个错误)?
答案 0 :(得分:8)
试试这个,它应该适合你
注意:我在 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:Strike + LineSpacing + Character Spacing