[iOS 問題集錦] UISearchController.searchBar becomeFirstResponder不生效

問題描述

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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容