繁体   English   中英

如何检测 UISearchBar/UITextField 的输入暂停?

[英]How to detect a pause in input for UISearchBar/UITextField?

我有以下 UISearchbar 代码:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSString* endpoint =[NSString stringWithFormat:@"http://www.someurl/",
                         [searchText stringByReplacingOccurrencesOfString:@" " withString:@"+"]];
    NSURL* url = [NSURL URLWithString:endpoint];
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    GTMHTTPFetcher* myFetcher = [GTMHTTPFetcher fetcherWithRequest:request];
    [myFetcher beginFetchWithDelegate:self didFinishSelector:@selector(searchResultsFetcher:finishedWithData:error:)];
}

我想在输入暂停后发送此请求,并在每次击中字符时重置计时器。 我怎样才能做到这一点?

它不必使用 NSTimer。

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
        {
           [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(request) object:nil];

          //.....

           [self performSelector:@selector(request) withObject:nil afterDelay:yourpausetime];

        }

textDidChange方法中创建一个 NSTimer,比如说 2 秒。 如果计时器已经存在,则使计时器无效并重新创建。 (未经测试的代码:)

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (myTimer) {
        if ([myTimer isValid]) { [myTimer invalidate]; }
        [myTimer release], myTimer = nil;
    }
    myTimer = [[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(userPaused:) userInfo:nil repeats:NO] retain];
}

当用户停止输入 2 秒时,将调用 -userPaused: 并且您的计时器将自动失效(尽管不是 nil)。 当用户再次开始输入时,将设置一个新的计时器。

我能够将 Sven Tan 的答案改编为我在 Swift 中的现有代码。 就我而言,我将字符串发送到异步加载搜索结果的方法。 此外,我没有使用 UISearchBar,而是使用普通的旧 UITextField。

var currentTempQuery = ""

...

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if let t = textField.text {
        let s: NSString = t
        let newString = s.stringByReplacingCharactersInRange(range, withString: string).trim()

        NSObject.cancelPreviousPerformRequestsWithTarget(self, selector:#selector(MyViewController.sendSearchRequest(_:)), object: currentTermQuery)

        // Don't replace currentTermQuery until after the cancelPreviousPerformRequestWithTarget call
        currentTermQuery = newString
        performSelector(#selector(MyViewController.sendSearchRequest(_:)), withObject: newString, afterDelay: 1)
    }
    return true
}

这是被调用的选择器:

func sendSearchRequest(text: String?) {
    // Call async search method here...
}

cancelPreviousPerformRequestsWithTarget的工作方式是您需要传递在performSelector调用中传递的相同目标、选择器和 object,以便取消先前的请求。 在我的实现中,由于我只传递一个字符串,我需要在调用之间保留当前请求字符串,以便我可以引用它来取消请求。

结果适用于在我的 UITextField 中键入和删除字符。 每个主要搜索词更改仅发送一个搜索。

就像我说的,类似于 Sven Tan 发布的内容,但用法略有不同。 希望这可以帮助一些人。

优秀的代码和对我来说完美的工作。 我在这里找到了用 performSelector:withObject:afterDelay 替换 NSTimer 多亏了Ben的解决方案......所有赏金给他,我只是把它复制到这里,这样很容易找到

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //because the view can be unloaded we must store all data so that its state can be restored in viewDidLoad
    self.searchQuery = [textField.text stringByReplacingCharactersInRange:range withString:string];

    SEL fetchSearchResults = @selector(fetchSearchResults);

    //cancel the previous search request
    [[self class] cancelPreviousPerformRequestsWithTarget:self selector:fetchSearchResults object:nil];    

    //perform the search in a seconds time. If the user enters addition data then this search will be cancelled by the previous line
    [self performSelector:fetchSearchResults withObject:nil afterDelay:1];

    return YES;
}

- (void)fetchSearchResults
{
    NSLog(@"performing search %@", self.searchQuery);
    ...
}

阻止文本输入到您的搜索并让 NSTimer 调用选择器。 显示某种指标,这样用户就不会认为出了什么问题。 When the selector fires give control back to the user to continue typing

[NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(targetMethod:) userInfo:nil repeats:NO];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM