She*_*lam 15 iphone cocoa-touch objective-c nstimer uisearchbar
我有以下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:)];
}
Run Code Online (Sandbox Code Playgroud)
我希望在输入暂停后发送此请求,并在每次命中一个字符时重置计时器.我怎样才能做到这一点?
Sve*_*Tan 52
它不必使用NSTimer.
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(request) object:nil];
//.....
[self performSelector:@selector(request) withObject:nil afterDelay:yourpausetime];
}
Run Code Online (Sandbox Code Playgroud)
在该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];
}
Run Code Online (Sandbox Code Playgroud)
当用户停止键入2秒时,将调用-userPaused:并且您的计时器将自动失效(尽管不是nil).当用户再次开始键入时,将设置新的计时器.
| 归档时间: |
|
| 查看次数: |
6030 次 |
| 最近记录: |