1

I'm using a UITextField and I'd like to trigger a function when the user is taping in the textfield, but I want to wait 1/4sec before triggering the function.

How can I do that ?

Fabrice Froehly
  • 163
  • 1
  • 3
  • 10

1 Answers1

0

First, you have to create IBAction for example: changeTextField (see you screenshot)

screenshot: create an IBAction for Editing changed event

Second add this code

@IBAction func changeTextField(sender: AnyObject) {
    NSObject.cancelPreviousPerformRequestsWithTarget(self, selector: #selector(ViewController.functionWithDelay), object: nil)
    self.performSelector(#selector(ViewController.functionWithDelay),
                         withObject: nil,
                         afterDelay: 1/4);
}

Third, you function

func functionWithDelay() {
    print("running...")
}
David
  • 1,152
  • 16
  • 24
  • It's not working as I want. "functionWithDelay" is called everytime I hit the keyboard. I'd like the function to be called only when I'm not tapping for longer than 1/4sec – Fabrice Froehly Jul 19 '16 at 10:01
  • code update: I've add call to cancelPreviousPerformRequestsWithTarget if hit the keyboard before than 1/4sec – David Jul 19 '16 at 12:56