iOS 11:输入时UITextView typingAttributes重置

Bar*_*cki 12 uitextview ios ios11

typingAttributes用来设置一个新字体.在iOS的10,一切正常,但iOS的11,第一个输入的字符是正确的,但后来属性重置到以前的,而第二个字符键入与以前的字体.这是一个错误吗?我能以某种方式修复它吗?

Tun*_*Fam 9

使用时遇到内存使用问题 typingAttributes

此解决方案有效:

textField.defaultTextAttributes = yourAttributes // (set in viewDidLoad / setupUI)
Run Code Online (Sandbox Code Playgroud)

使用 TypingAttributes 有什么问题:在某个时间点,内存使用量上升并且从未停止并导致应用程序冻结。


Ser*_*nad 6

我遇到了同样的问题,最终通过在每次编辑后再次设置typingAttributes来解决它.

斯威夫特3

func textViewDidChange(_ textView: UITextView) {
    NotesTextView.typingAttributes = [NSForegroundColorAttributeName: UIColor.blue, NSFontAttributeName: UIFont.systemFont(ofSize: 17)]
}
Run Code Online (Sandbox Code Playgroud)


Fan*_*ing 6

为什么会这样:

Apple typingAttributes自iOS 11起更新

此字典包含要应用于新键入的文本的属性键(和相应的值).当文本视图的选择发生更改时,将自动清除字典的内容.

如何解决:

@Serdnad的代码有效,但会跳过第一个字符.在尝试了我能想到的一切之后,这是我的发现

1.如果您只想为文本视图使用一个通用输入属性

只需在此委托方法中设置一次输入属性,就可以使用此单一通用字体进行设置

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
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

2.在我的例子中,富文本编辑器的属性一直在变化:

在这种情况下,我必须在输入任何内容后每次都设置输入属性.感谢iOS 11的更新!

但是,不是在textViewDidChange方法中设置它,而是在shouldChangeTextIn方法中更好地工作,因为在将字符输入到文本视图之前调用它.

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
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述