6

希望有人可以对此有所了解。

我正在为一家公司开发一个应用程序,他们有一个自定义 UITextField 的搜索字段。目前,它使用输入的每个字母细化搜索。

问题:他们有一个小弹出窗口,表明它正在搜索,每次按键,您都会看到它在屏幕上闪烁。显然,他们不想要这个。

尽管不确定如何做,但我正在考虑做的不是在每个按键上完善搜索,而是在他们完成输入时进行搜索。但是,我也不想添加“搜索”按钮。我只希望他们完成打字,一秒钟,延迟或其他什么,搜索发生。

有没有办法检测用户何时完成输入?有人做过吗?

提前致谢。

4

3 回答 3

9

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.

于 2013-08-16T15:11:49.300 回答
5

使用 timerWithTimeInterval:target:selector:userInfo:repeats: 方法,您必须将计时器添加到运行循环。我需要编辑答案如下:

- (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;
}
于 2014-07-29T03:34:55.047 回答
0

您可以尝试以下方式

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

UITextField委托方法中

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
于 2013-08-16T15:18:08.353 回答