swiftuitextviewkerningnsmutableparagraphstyle

UITextView style is reset when I change kerning


The style is reset when I change kerning. For example, when I change the text size or color, it is saved, but when I change kerning, the style UITextView is reset


@IBAction func sizeTextEdit(_ sender: Any) {

        self.textOne?.font = UIFont.systemFont(ofSize: CGFloat(sizeText.value * 1))
    }

@IBAction func kernTextEdit(_ sender: Any) {

    let textString = textOne.text
    let attrs: [NSAttributedString.Key : Any] = [.kern: kernText.value]
        textOne?.attributedText = NSAttributedString(string: textString!, attributes: attrs)
    }

As you can see in the first screenshot, I increased the font, then I increased the distance between the letters and the font size was reset

enter image description here


Solution

  • The font property only changes the font for the text property. The attributedText is a different property, so you need to define the font for it too:

    let attrs: [NSAttributedString.Key : Any] = [.kern: kernText.value,
                                                 .font: UIFont.systemFont(ofSize: CGFloat(sizeText.value * 1))]
    textOne?.attributedText = NSAttributedString(string: textString!, attributes: attrs)
    

    On a side note, if you want to do a thing like this it's better to stick to one property, in this case attributedText, otherwise you have to keep them in sync.