我有以下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:)];
}我想在输入暂停后发送此请求,并在每次命中字符时重置计时器。我该怎么做呢?
发布于 2011-08-15 11:29:36
它不一定要使用NSTimer。
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(request) object:nil];
//.....
[self performSelector:@selector(request) withObject:nil afterDelay:yourpausetime];
}发布于 2011-08-15 11:45:19
在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:,并且您的计时器将自动失效(尽管不是空的)。当用户再次开始键入时,将设置一个新的计时器。
发布于 2016-06-06 22:37:24
我能够将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调用中传递的相同的目标、选择器和对象,以便取消先前的请求。在我的实现中,因为我只传递了一个字符串,所以我需要在调用之间保留当前的请求字符串,以便我可以引用它来取消请求。
结果适用于在我的UITextField中键入和删除字符。每个主要搜索词更改仅发送一个搜索。
就像我说的,与Sven Tan发布的类似,但用法略有不同。希望这能帮助一些人。
https://stackoverflow.com/questions/7061377
复制相似问题