前言
iOS8開始,蘋果引入了新的UISearchController替代UISearchDisplayController。iOS7已經廢棄一段時間了,所以研究了下UISearchController的使用,替換了目前項目中的一個搜索模塊,UISearchDisplayController的使用不再贅述,直接講解UISearchController。
1.UISearchController簡介
一個UISearchController對象通過與UISearchBar交互管理搜索結果的展示。當你有一個包含可搜索內容的VC,把UISearchController對象的searchBar嵌入到當前VC的布局中,當用戶與searchBar交互時,UISearchController自動展示你自定義的searchResultsController。
2.原理
一個UISearchController(SVC)需要兩個自定義的VC:第一個VC1展示可搜索的內容,第二個VC2展示搜索的結果。VC1通常是push或present出來的界面,VC2負責展示搜索的結果,當使用initWithSearchResultsController初始化一個SVC時,把VC2當做參數傳入,SVC會在適當的時候展示VC2。
每一個SVC都包含一個searchBar對象,必須把searchBar嵌入到VC1的布局中,當用戶點擊searchBar時,SVC會自動展示VC2。
當用戶在searchBar輸入時,SVC會通知遵循searchResultsUpdater協議的對象(一般是VC1或者VC2),通過searchResultsUpdater對應的方法就可以進行搜索,并將搜索的結果展示到VC2中。
如果想要自定義VC2的presentation或者dismissal,可以讓一個對象遵循的SVC的delegate,delegate有5個方法,分別對應VC2的5個狀態。
盡管UISearchController是一個VC,但不要直接present,如果非要present,把UISearchController包裝進UISearchContainerViewController,然后present UISearchContainerViewController。
3.實例
3.1 場景
從首頁進入搜索用戶界面(VC1),VC1會展示搜索框和推薦的用戶,點擊搜索框展現VC2,編輯搜索框會將搜索結果展現在VC2上。VC截圖如下:
3.2 VC1中實例化UISearchController和VC2
創建@property:
viewDidLoad中實例化對象:
3.3 VC2中實例化SVC的代理
創建@property:
代理方法:
4.手機截圖
5.結語
UISearchController介紹就到這里。