iOS13系统改变了UISearchBar内部subview的层次结构,本文主要实现修改背景颜色和圆角。
先上所有代码,格式调整不好。
主要就是从UISearchBar找到文本框控件然后设置样式
-(UISearchBar*)search{
if(!_search) {
_search= [[UISearchBaralloc]initWithFrame:CGRectMake(20,64+NAV_TOP_X,SCREEN_WIDTH-40,35)];
[self.search setSearchBarStyle:UISearchBarStyleMinimal];
[self.search setPlaceholder:@"药品商品名/拼音首字母"];
self.search.tintColor=HEISE_COLOR;
self.search.delegate=self;
// ** 自定义searchBar的样式 **
UITextField* searchField =nil;
// 注意searchBar的textField处于孙图层中
for(UIView* view in[_search.subviewsfirstObject].subviews) {
NSLog(@"UISearchBar:%@", view.class);
UIView*subview=view;
if(@available(iOS13.0, *)) {
if ([view isKindOfClass:NSClassFromString(@"UISearchBarBackground")]){
//去掉背景颜色
[((UIImageView*)view)setImage:nil];
}
if ([view isKindOfClass:NSClassFromString(@"_UISearchBarSearchContainerView")]){
//ios13输入文本框又往里移了一层
subview=[view.subviewsfirstObject];
}
}
if([subview isKindOfClass:[UITextField class]]) {
searchField = (UITextField*)subview;
// 删除searchBar输入框的背景
[searchFieldsetBackground:nil];
[searchFieldsetBorderStyle:UITextBorderStyleNone];
//设置文本框的背景颜色
searchField.backgroundColor=LINE_COLOR;
// 设置圆角
searchField.layer.cornerRadius=3;
searchField.layer.masksToBounds=YES;
break;
}
}
}
return _search;
}