最近项目中要求修改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,并加入了一个圆角和边框,效果如下:
dns77gvpR/1fna/s3729O51Lk5HpPPXLACKGTBcXEAvK1DfEIEANRbABBFFn3vQkCLXn2BwD/xojdeCEsAjjoCENyJrDwADiMpLYQpyHvewiEWDTYzE66/Iz3OzHRRi4x4J0zn3NzbOQBwMQB87Z+bmy2fm/tahjT7HoCLvot+ez4IAwBkI/4y2O36ZL0r+I/4C2Tm9w110bglAAAIt0lEQVR4nO3dXWsTyxsA8GdmdpvdpsHaJmpqUnxpa6sYKr4bFRR8qUUEL7zRO28EQaifwW/gV6gHFASvqigWtRcFBSv1yJGiqG1VbFqjsdlNszvznIvR6FFTD+e/G//a53fVJpOZTciTedlndll3dzdjDAghvxREBIBnz8YRwIjFYj/7eAgh/wvkP/sICCH/HQIAgKG7ZkLIrwkBGPXGhPzCGGM0qCbkd0BhTMivjQEzatwkIrquOzs7WyqVatw0IaGyLKuhocG27VqewUUEAKxFGOtVtOnpadd1a9AcIT9FqVSqdE62bcfjcfg4dw0RY4BYk964EsCIyBjjnLNPatA6ITWAnyil9JBzYmLCtu1EIhFywxB6b4yIExMT+g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zpVKJ9hsTokkplVKWZTU3NwebHPXno78gjKt/MMZ0nrPOAg+8fkJ+LZVASCQSIW2tC+UiPpXBAyJSJJOFTK9OA0AqlQp+VgwAAIhh4sMpmUwqpfRwIrxWCPm/Vfn+J5PJkJpARBbqHRWFELpPllJWskkJWQj0pmKdyJBKpcJbJGKMAQv/VmzpdNqyrHK5LKWsbJuujDQI+T3o+aPGOZdSlstly7LS6XQNmg795i+IqFfnpqenaVMRWQiklJZlxePxL3OiwoIAIV0Z8yt6dS4ejzPGENF1Xcdx6LZs5Ddj23Z9fb2+oyJ+TDcO/ZJvqC9wW8vBrW7LsizLsmrWKCG1VIse+AuMseCTMQkhtaR/MiiMCfmlsRDv4UQIqQEGUIsTToSQELGQs7gIIaFDYCzMLC5CSOgYAMDf3AhFHhfWMTMAAAAASUVORK5CYII=">
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;
}
运行效果:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。