Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 491
Milan Nosáľ Avatar asked Sep 12 '17 08:09

Milan Nosáľ


1 Answers

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

enter image description here

like image 142
Krunal Avatar answered Oct 13 '22 19:10

Krunal