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

我需要为UILabel提供的文本设置两个属性:字母之间的间距(kern)和它的删除线样式。 基于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,但不应用删除线样式。 如果我没有指定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 

结果:
模拟1:打击+线间距
Sim 2:Strike + LineSpacing +字符间距

在此处输入图像描述