我有UISearchController
和UISearchBar
。当用户没有触摸键盘时(当用户在键盘上写完文字时),我希望在3秒后调用功能。我搜索了这些信息,但我没有找到任何信息。我该怎么做?
答案 0 :(得分:3)
每次searchText更改时,您可以通过启动计时器并延迟搜索方法来使用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
}