Search code examples
iosswiftuitextviewuitextviewdelegate

How to remember text attributes in UITextView when the user starts typing


I'm using a UITextView and I'm trying to have the text displayed using the attributedText property as the user types.

Here's my current code:

textView.attributedText = NSMutableAttributedString(
    string: "",
    attributes: [
        NSFontAttributeName: UIFont(name: "AvenirNextLTPro-Regular", size: 12.5)!,
        NSForegroundColorAttributeName: UIColor.colorFromCode(0x262626),
        NSKernAttributeName: 0.5,
        NSParagraphStyleAttributeName: paragraphStyle
    ]
)

The problem is that if you supply an empty string, when the user starts typing, the text isn't being formatted with the attributedText properties.

However, I noticed if I supply a string, as the user begins to append that string, the text is formatted with the attributedText properties.

The only way I can think to accomplish what I need would be to override this function and set the text to attributedText everytime a user enters a key:

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool

Is there no other better way to do this?


Solution

  • Instead of setting an empty attributed string you need to use the typingAttributes property.

    textView.typingAttributes = [
        NSFontAttributeName: UIFont(name: "AvenirNextLTPro-Regular", size: 12.5)!,
        NSForegroundColorAttributeName: UIColor.colorFromCode(0x262626),
        NSKernAttributeName: 0.5,
        NSParagraphStyleAttributeName: paragraphStyle
    ]
    

    See also the official documentation.

    The attributes to apply to new text being entered by the user.