Kevin Sabbe
Kevin Sabbe

Reputation: 1452

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 !

Upvotes: 3

Views: 1398

Answers (2)

Rob
Rob

Reputation: 437882

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
    }
}

Upvotes: 6

Mr. Xcoder
Mr. Xcoder

Reputation: 4795

First make sure to make your class the TextField's delegate:

class yourClass: UIViewController, UITextFieldDelegate{
    //...
}

And then in viewDidLoad():

textField.delegate = self
numbersTextField.addTarget(self, action: #selector(self.textFieldDidChange), for: .editingChanged)

After that, you can use a timer, like this:

var timer = Timer()
var count = 0

func textFieldDidChange(textField: UITextField){
     timer.invalidate()
     timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.timerFunc), userInfo: nil, repeats: true)
}

func timerFunc(){
    count += 1
    if count == 5{
        timer.invalidate()
        // do your things here down here, I assumed that your method is called autocomplete
        autocomplete()
    }
}

Hope it helps!

Upvotes: 2

Related Questions