SearchBar的那些事
最近项目中要求修改searchbar的风格,查了一些资料,简单总结一下。
1. 修改searchbar背景和其中textfield的背景
mySearchBar.backgroundColor = [UIColor clearColor];
for (UIView *subview in mySearchBar.subviews) {
if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
[subview removeFromSuperview];
} else if ([subview isKindOfClass:[UITextField class]]) {
UITextField *searchField = (UITextField *)subview;
searchField.textColor = [UIColor whiteColor];
[searchField setBackground: [UIImage p_w_picpathNamed:@"search_1"]];//在这添加灰色的图片
[searchField setBorderStyle:UITextBorderStyleNone];
searchField.layer.cornerRadius = 15;
searchField.layer.masksToBounds = YES;
searchField.placeholder = @"搜索";
searchField.textColor = [UIColor lightGrayColor];
searchField.layer.borderWidth = 2;
searchField.layer.borderColor = [UIColor colorWithRed:30/255.0 green:30/255.0 blue:30/255.0 alpha:1].CGColor;
}
}
添加一个深灰色的背景图search_1.png,并加入了一个圆角和边框,效果如下:
2.点击搜索框后弹出取消按钮,修改取消按钮风格和搜索框边框颜色,需要实现searchbar的代理方法如下:
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
[searchBar setShowsCancelButton:YES animated:YES];
for(id cc in [searchBar subviews])
{
if([cc isKindOfClass:[UIButton class]])
{
UIButton *btn = (UIButton *)cc;
btn.layer.cornerRadius = 15;
btn.layer.masksToBounds = YES;
[btn setBackgroundImage:[UIImage p_w_picpathNamed:@"top_button"] forState:UIControlStateNormal];
[btn setBackgroundImage:[UIImage p_w_picpathNamed:@"top_button-hover"] forState:UIControlStateHighlighted];
[btn setTitle:@"取消" forState:UIControlStateNormal];
} else if ([cc isKindOfClass:[UITextField class]]) {
UITextField *searchField = (UITextField *)cc;
searchField.layer.borderWidth = 2;
searchField.layer.borderColor = [UIColor colorWithRed:56/255.0 green:173/255.0 blue:255/255.0 alpha:1].CGColor;
}
}
return YES;
}
运行效果:
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。