Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform action after slight delay when typing in UITextField

Hoping somebody can shed some light on this.

I'm working on an app for a company and they have a search field that is a custom UITextField. Presently it refines the search with each letter entered.

Problem: They have a little popup indicating that it's searching and with each keypress, you see it flash on and off the screen. They don't want this, obviously.

What I was thinking of doing although not sure how, is instead of refining the search on every keypress, searching when they're finished typing. BUT, I also don't want to have to add a "Search" button. I just want them to finish typing, one second, delay or something, search happens.

Is there a way to detect when the user has finished typing? Has anybody done this?

Thanks in advance.

like image 567
r0ddy Avatar asked Aug 16 '13 15:08

r0ddy


2 Answers

You could probably do this with a simple NSTimer. In shouldChangeCharactersInRange: check if the timer is valid and if it is, invalidate it, then restart the timer. When the time is finally aloud to fire, it means that the user hasn't typed anything in the interval you specify 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 pointed out in order to implement this method, you'll need to assign your controller as the delegate of of your UITextField and make sure your controller conforms to the UITextFieldDelegate protocol.

like image 88
Mick MacCallum Avatar answered Nov 09 '22 04:11

Mick MacCallum


With the method timerWithTimeInterval:target:selector:userInfo:repeats: you must add the timer to the 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;
}
like image 5
Josh Gafni Avatar answered Nov 09 '22 04:11

Josh Gafni