Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Textfield didChange with timer

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 !

like image 434
Kevin Sabbe Avatar asked Aug 02 '26 05:08

Kevin Sabbe


1 Answers

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
    }
}
like image 81
Rob Avatar answered Aug 04 '26 19:08

Rob