在進行ios開發的時候,有時候涉及到搜索功能,實現搜索功能的方法有不少,能夠是用自定義的搜索控件,也能夠用sdk提供的UISearchController(ios8之後)、UISearchDisplayController(ios8以前);ios
下面介紹UISearchController使用方法及注意事項:ide
_searchController = [[UISearchController alloc] initWithSearchResultsController:_viewController];spa
_searchController.searchResultsUpdater = self; //設置UISearchResultsUpdating協議代理代理
_searchController.delegate = self; //設置UISearchControllerDelegate協議代理orm
_searchController.dimsBackgroundDuringPresentation = NO; //是否添加半透明覆蓋層開發
_searchController.hidesNavigationBarDuringPresentation = YES; //是否隱藏導航欄it
[self.view addSubview:_searchController.searchBar]; //此處重要一步,將searbar顯示到界面上io
另外須要注意在合適的地方添加下面一行代碼渲染
self.definesPresentationContext = YES;date
這行代碼是聲明,哪一個viewcontroller顯示UISearchController,蘋果開發中心的demo中的對這行代碼,註釋以下
// know where you want UISearchController to be displayed
a、若是不添加上面這行代碼,在設置hidesNavigationBarDuringPresentation這個屬性爲YES的時候,搜索框進入編輯模式會致使,searchbar不可見,偏移-64;
在設置爲NO的時候,進入編輯模式輸入內容會致使高度爲64的白條,猜想是導航欄沒有渲染出來
b、若是添加了上面這行代碼,在設置hidesNavigationBarDuringPresentation這個屬性爲YES的時候,輸入框進入編輯模式正常顯示和使用;在設置爲NO的時候,搜索框進入編輯模式致使向下偏移64,具體緣由暫時未找到