Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS 11: UITextView typingAttributes reset when typing

I use typingAttributes to set a new font. On iOS 10, everything works, but on iOS 11, first typed character is correct, but then attributes are being reset to the previous ones, and the second character is typed with the previous font. Is this a bug? Can I fix it somehow?

like image 824
Bartosz Bialecki Avatar asked Sep 26 '17 07:09

Bartosz Bialecki


3 Answers

Why this happened:

Apple updated typingAttributes since iOS 11

This dictionary contains the attribute keys (and corresponding values) to apply to newly typed text. When the text view’s selection changes, the contents of the dictionary are cleared automatically.

How to fix it:

@Serdnad's code works but it will skip the first character. Here is my finding after trying everything that I can possibly think of

1. If you just want one universal typing attribute for your text view

Simply set the typing attribute once in this delegate method and you are all set with this single universal font

func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
    //Set your typing attributes here
    textView.typingAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.blue, NSAttributedStringKey.font.rawValue: UIFont.systemFont(ofSize: 17)]
    return true
}

enter image description here

2. In my case, a Rich Text Editor with attributes changeinge all the times:

In this case, I do have to set typing attributes each and every time after entering anything. Thank you iOS 11 for this update!

However, instead of setting that in textViewDidChange method, doing it in shouldChangeTextIn method works better since it gets called before entering characters into the text view.

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    textView.typingAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.blue, NSAttributedStringKey.font.rawValue: UIFont.systemFont(ofSize: 17)]
    return true
}

enter image description here

like image 198
Fangming Avatar answered Nov 10 '22 14:11

Fangming


Had issues with memory usage while using typingAttributes

This solution worked:

textField.defaultTextAttributes = yourAttributes // (set in viewDidLoad / setupUI)

What was the problem with using typingAttributes: at some point in time, the memory usage went up and never stopped and caused the app to freeze.

like image 45
Tung Fam Avatar answered Nov 10 '22 14:11

Tung Fam


I ran into the same issue and eventually solved it by setting typingAttributes again after every edit.

Swift 3

func textViewDidChange(_ textView: UITextView) {
    NotesTextView.typingAttributes = [NSForegroundColorAttributeName: UIColor.blue, NSFontAttributeName: UIFont.systemFont(ofSize: 17)]
}
like image 7
Serdnad Avatar answered Nov 10 '22 14:11

Serdnad