一舞痰、簡介
UISearchController
是iOS 8 之后推出的一個新的控件, 用于創(chuàng)建搜索條, 及管理搜索事件土榴,一般不單獨使用。都是與tableView 結(jié)合使用响牛。
二玷禽、屬性及方法
-
初始化方法
initWithSearchResultsController (nullable UIViewController *)
參數(shù)為空,表示使用當(dāng)前控制器作為展示結(jié)果的控制器呀打。否則矢赁,使用指定的控制器作為顯示結(jié)果的控制器 兩個代理
(1)UISearchControllerDelegate
該代理中的方法用來告知用戶結(jié)果視圖的狀態(tài)(即將出現(xiàn),已經(jīng)出現(xiàn)贬丛,即將消失撩银,已經(jīng)消失);
(2)UISearchResultsUpdating
該代理中updateSearchResultsForSearchController
方法每輸入一個字符就會執(zhí)行該方法一次豺憔,在此方法中進(jìn)行數(shù)據(jù)的更新及表視圖的刷新屬性
// active 屬性就是當(dāng)前 searchController 是不是處于激活狀態(tài).只要點擊 searchBar,active 就會被置為 true.
@property (nonatomic, assign, getter = isActive) BOOL active;
// 搜索框额获,根據(jù)需求可進(jìn)行自定義
@property (nonatomic, strong, readonly) UISearchBar *searchBar;
// 只讀屬性,展示結(jié)果的視圖控制器
@property (nullable, nonatomic, strong, readonly) UIViewController *searchResultsController;
// 搜索時,背景是否變暗色 恭应,默認(rèn)為YES
@property (nonatomic, assign) BOOL dimsBackgroundDuringPresentation
// 搜索時抄邀,背景是否變模糊 默認(rèn)為YES
@property (nonatomic, assign) BOOL obscuresBackgroundDuringPresentation NS_AVAILABLE_IOS(9_1);
// 是否隱藏導(dǎo)航欄,默認(rèn)為YES
@property (nonatomic, assign) BOOL hidesNavigationBarDuringPresentation;
- 個性化設(shè)置
// 通過此種方式可以獲取到searchBar內(nèi)部的輸入框昼榛,根據(jù)需要可對其進(jìn)行個性化設(shè)置
UITextField *searchTextField = [self.systemSearchController.searchBar valueForKey:@"_searchField"];
三境肾、代理
- UISearchControllerDelegate
//當(dāng)自動呈現(xiàn)或刪除發(fā)生時,調(diào)用這些方法。如果自己呈現(xiàn)或取消搜索控制器准夷,它們將不會被調(diào)用钥飞。
- (void)willPresentSearchController:(UISearchController *)searchController;
- (void)didPresentSearchController:(UISearchController *)searchController;
- (void)willDismissSearchController:(UISearchController *)searchController;
- (void)didDismissSearchController:(UISearchController *)searchController;
// 在搜索控制器的搜索欄同意開始編輯或“active”被設(shè)置為YES時調(diào)用。如果您選擇不呈現(xiàn)控制器或不實現(xiàn)此方法衫嵌,則將代表您執(zhí)行默認(rèn)表示读宙。
- (void)presentSearchController:(UISearchController *)searchController;
四、使用系統(tǒng)搜索控制器所遇到的坑及解決方式
1楔绞、搜索結(jié)果頁tableView向下偏移结闸,如圖:
解決方法:
第一個界面添加:
self.definesPresentationContext = YES;
第二個界面添加:
self.edgesForExtendedLayout =UIRectEdgeNone;
- warning 如果進(jìn)入預(yù)編輯狀態(tài),searchBar消失(UISearchController套到?TabBarController可能會出現(xiàn)這個情況),請?zhí)砑酉逻呥@句話</color>
self.definesPresentationContext = YES;
- iOS11之后searchController有了新樣式,可以放在導(dǎo)航欄
if (@available(iOS 11.0, *)) {
self.navigationItem.searchController = self.searchController;
} else {
self.tableView.tableHeaderView = self.searchController.searchBar;
}
- 在iOS 11上運行tableView向下偏移64px或者20px酒朵,因為iOS 11廢棄了automaticallyAdjustsScrollViewInsets桦锄,而是給UIScrollView增加了contentInsetAdjustmentBehavior屬性。避免這個坑的方法是要判斷
if (@available(iOS 11.0, *)) {
_tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
}else {
self.automaticallyAdjustsScrollViewInsets = NO;
}