I'm working on autocompletion in my project and I would like to detect when the textfieldDidChange value and call a method (link to API) 500MS after that.
I hope it's clear enough Thank for your help !
In Swift 3, you probably want to connect to "editing changed" not "value changed", and reset the timer and start another timer:
weak var timer: Timer?
@IBAction func didChangeEditing(_ sender: UITextField) {
timer?.invalidate()
timer = .scheduledTimer(withTimeInterval: 0.5, repeats: false) { [weak self] timer in
// trigger your autocomplete
}
}
Or you can alternatively hook into shouldChangeCharactersIn. For example:
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self // or you can do this in IB
}
weak var timer: Timer?
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
timer?.invalidate() // cancel prior timer, if any
timer = .scheduledTimer(withTimeInterval: 0.5, repeats: false) { [weak self] timer in
// trigger your autocomplete
}
return true
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With