我有UISearchController
和UISearchBar
在里面。我想在3秒钟后,当用户不触摸键盘时(当用户完成在键盘上写文本时),调用函数。我搜索了这些信息,但没有找到任何信息。我怎么能做到?
最佳答案
您可以使用searchBar textDidChange
方法,方法是在每次搜索文本更改时启动计时器并延迟搜索方法:
目标c:
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
[searchDelayer invalidate];
searchDelayer=nil;
searchDelayer = [NSTimer scheduledTimerWithTimeInterval:3
target:self
selector:@selector(doDelayedSearch:)
userInfo:searchText
repeats:NO];
}
-(void)doDelayedSearch:(NSTimer *)t
{
assert(t == searchDelayer);
[self request:searchDelayer.userInfo]; // your search method
searchDelayer = nil;
}
别忘了在
NSTimer *searchDelayer
文件中添加.h
。银行代码:
var searchDelayer: NSTimer
override func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
searchDelayer.invalidate()
searchDelayer = nil
searchDelayer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "doDelayedSearch", userInfo: searchText, repeats: false)
}
func doDelayedSearch(t: NSTimer) {
assert(t == searchDelayer)
self.request(searchDelayer.userInfo)
searchDelayer = nil
}