說明:本文主要是將系統UISearchController控件聲明文件中的屬性、方法、代理等介紹下,后續再聯合【搜索欄UISearchBar】這篇文章一起更新更實用的信息。
1、初始化
// 如果設置searchResultsController參數為nil,代表搜索后的結果不顯示在當前控制器之上 - (instancetype)initWithSearchResultsController:(UIViewController *)searchResultsController;
2、代理
@property(nonatomic, weak) id<UISearchControllerDelegate> delegate;
UISearchControllerDelegate:
// 當用戶在搜索控制器中開始編輯時或者將active屬性設置為YES時,該方法被調用 - (void)presentSearchController:(UISearchController *)searchController; // 當搜索控制器即將出現時 - (void)willPresentSearchController:(UISearchController *)searchController; // 當搜索控制器已經出現時 - (void)didPresentSearchController:(UISearchController *)searchController; // 當搜索控制器即將消失時 - (void)willDismissSearchController:(UISearchController *)searchController; // 當搜索控制親已經消失時 - (void)didDismissSearchController:(UISearchController *)searchController;
3、管理搜索結果
// 在呈現搜索控制器執之前,將搜索欄放置在視圖控制器界面的某個位置。點擊搜索欄為起點。與搜索欄的交互是由UISearchController自動處理的 @property(nonatomic, strong, readonly) UISearchBar *searchBar; // 該協議是用來監控將搜索結果傳遞到搜索結果控制器的過程的 @property(nonatomic, weak) id<UISearchResultsUpdating> searchResultsUpdater; // 搜索結果控制器 @property(nonatomic, strong, readonly) UIViewController *searchResultsController; // 當用戶點擊搜索欄后,搜索控制器會出現,並且搜索結果控制器也會自動的顯示出來。通常利用這個屬性是為了確定當前是否顯示了搜索結果。但是也可以將此屬性設置為YES,這樣就會強制顯示出搜索界面。 默認為NO @property(nonatomic, assign, getter=isActive) BOOL active;
UISearchResultsUpdating:
// 只要搜索欄成為第一響應者或者對搜索欄中的文本進行更改,就會自動調用此方法。在此方法中進行過濾或者更新 - (void)updateSearchResultsForSearchController:(UISearchController *)searchController;
4、配置搜索界面
// 當此屬性為YES時,只要用戶與搜索欄進行交互,搜索控制器就會遮住包含可搜索內容的視圖控制器。當此屬性為NO時,搜索控制器不會遮住原始視圖控制器。該屬性僅僅是控制原始視圖控制器是否最初被遮擋。當用戶開搜索欄中輸入文本時,搜索控制器就會立即顯示搜索結果控制器和結果。 // 如果使用同一個控制器來顯示可搜索內容和搜索結果,建議將此屬性設置為NO。此屬性的默認為YES @property(nonatomic, assign) BOOL obscuresBackgroundDuringPresentation; // 在搜索過程中底層內容是否變暗 @property(nonatomic, assign) BOOL dimsBackgroundDuringPresentation; // 當出現搜索控制器的時候是否隱藏導航欄。默認為YES @property(nonatomic, assign) BOOL hidesNavigationBarDuringPresentation;
二、使用過程中注意的問題
1、如果將UISearchController中的屬性searchBar作為導航欄的titleView,在iOS11以后,導航欄的高度將不再是44,而是56。接下來的話,需要對導航欄上面的其他控件,比如返回按鈕重新進行位置的調整。
