iOS 11: UITextView typingAttributes reset when typing

最后都变了- 提交于 2019-12-03 02:22:56

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)]
}

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
}

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
}

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.

From iOS 11, Apple clear the attributes after every character.

When the text view’s selection changes, the contents of the dictionary are cleared automatically.

https://developer.apple.com/documentation/uikit/uitextview/1618629-typingattributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!