首先初始化,這就不細說了,三個代理都寫上:
_searchController.searchResultsUpdater = self; _searchController.searchBar.delegate = self; _searchController.delegate = self;
一、自動彈出鍵盤
以往的寫法:
- (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; self.searchController.active = true; } - (void)didPresentSearchController:(UISearchController *)searchController { [self.searchController.searchBar becomeFirstResponder]; }
實現如上的代碼就可以了,但是如果把searchbar寫到導航條上,發現這么寫完全是沒作用的。修改:
- (void)didPresentSearchController:(UISearchController *)searchController { [UIView animateWithDuration:0.1 animations:^{} completion:^(BOOL finished) { [self.searchController.searchBar becomeFirstResponder]; }]; }
二、搜索輸入時禁止searchBar上移隱藏導航條
_searchController.hidesNavigationBarDuringPresentation = NO;
三、修改searchBar取消按鈕的顏色和文字
[[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:[UIColor whiteColor]]; [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTitle:@"取消"];
四、顯示searBar的光標(如果不顯示可以這么設置)
_searchController.searchBar.tintColor = [UIColor blueberryColor];
