如何知道用户没有触摸键盘?

时间:2015-10-15 12:49:49

标签: ios swift keyboard swift2

我有UISearchControllerUISearchBar。当用户没有触摸键盘时(当用户在键盘上写完文字时),我希望在3秒后调用功能。我搜索了这些信息,但我没有找到任何信息。我该怎么做?

1 个答案:

答案 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
}