Perform an action after a short delay when entering in a UITextField

Hoping someone can shed some light on this.

I am working on an application for a company and they have a search field that is a custom UITextField. He is currently refining the search with each letter entered.

Problem: they have a small pop-up window indicating what it is looking for and with each keystroke, you see that it is blinking and turning off. They don’t want it, obviously.

What I was thinking of doing, but not sure how to do it, instead of refining the search at each key press, look for when they finish typing. BUT, I also do not want to add the "Search" button. I just want them to finish typing, one second, delay or something, the search is happening.

Is there any way to detect when the user has finished typing? Has anyone done this?

Thanks in advance.

+6
source share
3 answers

Perhaps you can do this with a simple NSTimer. In shouldChangeCharactersInRange: check if the timer is valid, and if it is, invalid, then restart the timer. When the time finally lights up aloud, this means that the user has not typed anything in the interval you specified for the time.

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (someTimer.isValid) { [someTimer invalidate]; } someTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timeToSearchForStuff:) userInfo:nil repeats:NO]; return YES; } 

As @Jai Govindani explained, to implement this method, you need to designate your controller as a delegate of your UITextField and make sure that your controller complies with the UITextFieldDelegate protocol.

+8
source

Using the timerWithTimeInterval: target: selector: userInfo: repeat: method, you must add a timer to runloop. I needed to edit the answer as follows:

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ if (someTimer.isValid) { [someTimer invalidate]; } someTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timeToSearchForStuff:) userInfo:nil repeats:NO]; [[NSRunLoop mainRunLoop] addTimer:someTimer forMode:NSDefaultRunLoopMode]; return YES; } 
+5
source

You can try the following:

 [self performSelector:<your selector> withObject:<object if you want to pass anything> afterDelay:<time delay>]; 

in UITextField delegate method

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
0
source

Source: https://habr.com/ru/post/951894/


All Articles