1

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?

hennes
  • 9,147
  • 4
  • 43
  • 63
Thomas
  • 2,356
  • 7
  • 23
  • 59

1 Answers1

4

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.

hennes
  • 9,147
  • 4
  • 43
  • 63
  • Is there a way to do something similar with a UILabel? For example, I have a UILabel with no text in it, but as I parse my JSON I'm adding to text to it – Thomas Aug 11 '15 at 20:38
  • 1
    @Thomas I'm afraid not. On a `UILabel` you have to use the `attributedText` property. – hennes Aug 12 '15 at 09:11