When I tap on "Hello" or "He", textViewDidChange is not triggered.
How to detect when predictive text is selected?
When I tap on "Hello" or "He", textViewDidChange is not triggered.
How to detect when predictive text is selected?
Try using shouldChangeTextInRange
instead of textViewDidChange
I tried it and it is triggered with predictive text
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()
}
}
Do you have set textView.delegate ?
YourViewController<UITextViewDelegate>
textView.delegate = self
func textViewDidChange(textView: UITextView)
:
func textViewDidChange(textView: UITextView) {
//textView(Sender)
if(textView == yourtextview) {
//do something
}
}