7

enter image description here

When I tap on "Hello" or "He", textViewDidChange is not triggered.

How to detect when predictive text is selected?

Alex
  • 881
  • 2
  • 10
  • 24

4 Answers4

1

Try using shouldChangeTextInRange instead of textViewDidChange I tried it and it is triggered with predictive text

user3126427
  • 855
  • 2
  • 14
  • 29
  • shouldChangeTextInRange does reflect when auto complete is used, but Im not able to differentiate cursor position change with auto complete, as both event triggers shouldChangeTextInRange – Alex Aug 06 '16 at 17:24
1

I had to use the NotificationCenter to get notified when a UITextView changes. I've created an extension of UITextView to register/unregister for those notifications. Just remember to call unregister when you would no longer want to keep handling those changes (E.g. on viewWillDisappear).

import UIKit

extension UITextView {

    public func registerTextViewNotifications() {
        let center = NotificationCenter.default
        center.addObserver(self,
                           selector: #selector(textViewDidChangeWithNotification(_:)),
                           name: UITextView.textDidChangeNotification,
                           object: nil)
    }

    public func unregisterTextViewNotifications() {
        let center = NotificationCenter.default
        center.removeObserver(self,
                              name: UITextView.textDidChangeNotification,
                              object: nil)
    }

    @objc private func textViewDidChangeWithNotification(_ notification: Notification) {
        // Do something when edited
        print("Text: \(String(describing: text))")
    }

}

class ViewController: UIViewController {

    @IBOutlet var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        textView.registerTextViewNotifications()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        textView.unregisterTextViewNotifications()
    }

}
odm
  • 888
  • 1
  • 14
  • 22
0

Do you have set textView.delegate ?

  • Yep! textViewDidChange is triggered as I typed but when I use the predictive text, textViewDidChange is not triggered. – Alex Aug 01 '16 at 01:31
0
  1. YourViewController<UITextViewDelegate>
  2. After setup the textView, textView.delegate = self
  3. func textViewDidChange(textView: UITextView): func textViewDidChange(textView: UITextView) { //textView(Sender) if(textView == yourtextview) { //do something } }
Tony
  • 542
  • 3
  • 13