-
旧样式
UISearchController中SearchBar的旧有样式并不能满足,所以需要开发者对其做一定的修改,包括icon、文字、背景颜色等属性。
旧样式-不够时尚.png
-
新样式
未输入状态.png
搜索状态.png
- (void)configSearchBar {
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.searchBar.placeholder = @"It's new style.";
self.searchController.searchBar.showsCancelButton = YES;
self.searchController.searchBar.showsBookmarkButton = YES;
self.tableView.tableHeaderView = self.searchController.searchBar;
// 重新设置searchBar部分属性
// 1. 修改搜索框圆角属性、边框
UIView *SearchBarSearchFieldBackgroundView = [self subViewOfClassName:@"_UISearchBarSearchFieldBackgroundView" withView:self.searchController.searchBar];
if (SearchBarSearchFieldBackgroundView) {
SearchBarSearchFieldBackgroundView.layer.cornerRadius = 18;
SearchBarSearchFieldBackgroundView.layer.borderColor = [UIColor darkGrayColor].CGColor;
SearchBarSearchFieldBackgroundView.layer.borderWidth = 0.5;
SearchBarSearchFieldBackgroundView.clipsToBounds = YES;
}
// 2. 修改颜色
self.searchController.searchBar.tintColor = [UIColor whiteColor]; // 修改了右侧按钮的文字颜色、光标颜色
self.searchController.searchBar.barTintColor = [UIColor colorWithRed:200/255.0 green:100/255.0 blue:180/255.0 alpha:1.0]; // 搜索框背景色
// 3. 修改左侧放大镜、右侧booksicon(也可以修改clearButtonImage)
[self.searchController.searchBar setImage:[UIImage imageNamed:@"clock"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
[self.searchController.searchBar setImage:[UIImage imageNamed:@"clock"] forSearchBarIcon:UISearchBarIconBookmark state:UIControlStateNormal];
// 4. 搜索框文字颜色及背景色
UITextField *textField = (UITextField *)[self subViewOfClassName:@"UISearchBarTextField" withView:self.searchController.searchBar];
if (textField) {
textField.textColor = [UIColor redColor]; // 搜索框文字的颜色
// textField.backgroundColor = [[UIColor orangeColor] colorWithAlphaComponent:0.1]; // 搜索框背景色
}
// 5. 修改右侧取消按钮的相关属性
UIButton *navigationButton = (UIButton *)[self subViewOfClassName:@"UINavigationButton" withView:self.searchController.searchBar];
if (navigationButton) {
[navigationButton setTitle:@"rightButton" forState:UIControlStateNormal];
// 优先级高于barTintColor对button文字颜色的修改
[navigationButton setTintColor:[UIColor blackColor]];
navigationButton.backgroundColor = [[UIColor orangeColor] colorWithAlphaComponent:0.3];
}
}
- (UIView*)subViewOfClassName:(NSString*)className withView:(UIView *)view{
for (UIView* subView in view.subviews) {
if ([NSStringFromClass(subView.class) isEqualToString:className]) {
return subView;
}
UIView* resultFound = [self subViewOfClassName:className withView:subView];
if (resultFound) {
return resultFound;
}
}
return nil;
}
-
补充
遍历来遍历去,我觉得想要一个自定义性更强的searchBar,最好还是用其它控件自定义(譬如:textField),搜索图标,右侧取消按钮都可以自定义。
-
参考: