观察 UITextView 子类中的文本

Observe text in subclass of UITextView

我要观察var文本! 属性 的 UITextView,我不想使用委托。

我的解决方案是这样的:

class MessageTextView: UITextView {

override var text: String! {
        didSet {
            print(text)
        }
    }
}

但在 UITextView 的文本字段中键入时不会调用它。 我也尝试了 textStorage 和 selectedRange。对我来说,覆盖文本才有意义,但它不起作用。有什么解决办法吗?

编辑: 这是我的解决方案:

deinit {

        NotificationCenter.default.removeObserver(self, name: UITextView.textDidChangeNotification, object: nil)
    }

    func setObserverNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(updateText), name: UITextView.textDidChangeNotification, object: nil)
    }

    @objc private func updateText() {
      // Do updates here
    } 

For me it only makes sense to override text, but it does not work.

UITextView 似乎不太可能实际设置您每次键入字符时尝试覆盖的任何属性。文本视图的实际内容保存在 UITextStorage 对象中,创建一次并根据需要进行修改,因此 textStorage setter 的重写最多只调用一次,而不是每次你打字。由于编辑,text setter 根本不会被调用——您可以调用它来获取或设置内容,但编辑不会更改整个内容。

如果您想了解文本视图何时收到通知但又不想使用委托,那么您可以改用监听通知。 UITextViewTextDidChangeNotification 每当文本发生更改时都会发送。