如何为`UILabel`设置字符(kern)和删除线样式之间的间距?

时间:2017-09-12 08:57:02

标签: ios swift ios10 swift4 nsattributedstring

我需要为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属性),则删除线样式有效。

任何人都有不同的方法来解决这个错误(我认为这是一个错误)?

1 个答案:

答案 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

enter image description here