How to set both spacing between characters (kern) and strikethrough style for `UILabel`?

放肆的年华 提交于 2019-12-10 14:32:24

问题


I need to set two attributes to a text presented by a UILabel: spacing between letters (kern), and its strikethrough style. Based on the NSAttributedStringKey documentation I have created the following extension to the 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)
    }
}

However, it seems that .kern key somehow collides with the .strikethroughStyle key, because if I specify kern, the kern is applied, but not the strikethrough style. If I don't specify kern (so the extension does not apply the .kern attribute), the strikethrough style works.

Anyone has a different way how to work around this bug (I assume this is a bug)?


回答1:


Try this, it should work for you
Note: I tested in 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


Result:
Sim 1: Strike + LineSpacing
Sim 2: Strike + LineSpacing + Character Spacing



来源:https://stackoverflow.com/questions/46172079/how-to-set-both-spacing-between-characters-kern-and-strikethrough-style-for-u

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!