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

Mil*_*sáľ 5 nsattributedstring ios swift ios10 swift4

我需要为一个文本设置两个属性UILabel:a .字母间隔(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)
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,似乎.kern键以某种方式与键碰撞.strikethroughStyle,因为如果我指定kern,则应用kern,但不应用删除线样式.如果我没有指定kern(因此扩展名不应用该.kern属性),删除线样式将起作用.

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

Kru*_*nal 9

试试这个,它应该适合你
注意:我在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
Run Code Online (Sandbox Code Playgroud)


结果:
Sim 1:Strike + LineSpacing
Sim 2:Strike + LineSpacing + Character Spacing

在此输入图像描述