How to differentiate between user-typed text vs programmatic calls to insertText(_:) in UITextView subclass?

Hi all,

I’m subclassing UITextView and overriding insertText(_:) to intercept and log input:


class TWTextView: UITextView {
    override func insertText(_ text: String) {
        print("insertText() : \(text)")
        super.insertText(text)
    }
}

This works fine, but I’ve noticed that insertText(_:) is invoked both when:

  1. The user types something in the text view (via hardware/software keyboard).
  2. I programmatically call myTextView.insertText("Hello") from my own code.

I’d like to be able to distinguish between these two cases — i.e., know whether the call was triggered by the user or by my own programmatic insert.

Is there any recommended way or system-provided signal to differentiate this?

Thanks in advance!

Just an idea, but I didn't try yet.

  • create a Bool stat var userTyped
  • in insert, test for userTyped
  • Each time you set text programmatically, userTyped = false
  • add a modifier to the TextField
      TextField(/* parameters*/)
        .onKeyPress(action: {keyPress in
          userTyped = true
        })

Please tell if it works.

How to differentiate between user-typed text vs programmatic calls to insertText(_:) in UITextView subclass?
 
 
Q