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?
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.
@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.
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)]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With