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

I need to set two attributes in the text represented UILabel: the distance between the letters (kern) and its strikethrough style. Based on the documentation NSAttributedStringKey, I created the following extension for 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 the key .kernsomehow collides with the key .strikethroughStyle, because if I specify kern, the kernel is applied, but not the strikethrough style. If I don't specify kern (so the extension does not apply the attribute .kern), the strikethrough style works.

Anyone have another way how to get around this error (I assume this is an error)?

+3
source share
1 answer

,
: 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 +

enter image description here

+4

Source: https://habr.com/ru/post/1693704/


All Articles