1

I want to observe the var text! property of UITextView, I do not want to use a delegate.

My solution is this:

class MessageTextView: UITextView {

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

But it does not get called when typing in the textfield of the UITextView. I tried textStorage and selectedRange as well. For me it only makes sense to override text, but it does not work. Any solution?

Edit: This is my solution:

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
    } 
PaFi
  • 888
  • 1
  • 9
  • 24

1 Answers1

4

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

It seems unlikely that a UITextView actually sets any of the properties that you tried to override every time you type a character. The actual content of a text view is kept in a UITextStorage object, and that's created once and modified as necessary, so an override of the textStorage setter is going to be called once at best, not every time you type. The text setter won't get called at all due to edits -- you can call it to get or set the contents, but edits don't change the entire content.

If you want to find out when a text view is notified but don't want to use a delegate, than you can listen for notifications instead. UITextViewTextDidChangeNotification gets sent whenever there's a change to the text.

Caleb
  • 124,013
  • 19
  • 183
  • 272