問題描述
UISearchController是iOS提供的最新的方便實現搜索框和搜索結果頁的組件,但是大家往往需要在進入這個頁面時候就讓搜索框獲得焦點并彈出鍵盤,提供給用戶更好的體驗
解決方案
各種google stackoverflow之后按照以下代碼達到了想要的效果(我是將searchbar放在navigationBar上的):
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear: animated];
self.searchController.active = true;
}
#pragma mark UISearchControllerDelegate
- (void)didPresentSearchController:(UISearchController *)searchController {
[self.searchController.searchBar becomeFirstResponder]
}
查看文檔,大家很容易明白這樣做的原理
需要注意的是:一定是在viewDidAppear中active searchController
測試iOS 8上沒有問題,但是iOS 9無法彈出鍵盤,又是一番查找,將代碼修改如下解決問題:
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear: animated];
self.searchController.active = true;
}
#pragma mark UISearchControllerDelegate
- (void)didPresentSearchController:(UISearchController *)searchController {
[UIView animateWithDuration:0.1 animations:^{} completion:^(BOOL finished) {
[self.searchController.searchBar becomeFirstResponder];
}];
}
分析原因,didPresentSearchController應該是在searchController被present出來完成后調用,但是事實估計是還沒有結束就調用了,所以里面執行becomeFirstResponder沒有生效,延時解決問題(并不一定是根本原因)
附效果圖
Paste_Image.png