自定义UISearchBar外观
1. 设置背景色
我以白色的背景色为例,下面看看代码:
//1. 设置背景颜色 //设置背景图是为了去掉上下黑线 self.customSearchBar.backgroundImage = [[UIImage alloc] init]; // 设置SearchBar的颜色主题为白色 self.customSearchBar.barTintColor = [UIColor whiteColor];
2. 设置边框颜色和圆角
//2. 设置圆角和边框颜色
UITextField *searchField = [self.customSearchBar valueForKey:@"searchField"];
if (searchField) {
[searchField setBackgroundColor:[UIColor whiteColor]];
searchField.layer.cornerRadius = 14.0f;
searchField.layer.borderColor = [UIColor colorWithRed:247/255.0 green:75/255.0 blue:31/255.0 alpha:1].CGColor;
searchField.layer.borderWidth = 1;
searchField.layer.masksToBounds = YES;
}
这段代码有个特别的地方就是通过KVC获得到UISearchBar的私有变量
searchField(类型为UITextField),设置SearchBar的边框颜色和圆角实际上也就变成了设置searchField的边框颜色和圆角,你可以试试直接设置SearchBar.layer.borderColor和cornerRadius,会发现这样做是有问题的。
3. 设置按钮(取消按钮)的文字和文字颜色
//3. 设置按钮文字和颜色 [self.customSearchBar fm_setCancelButtonTitle:@"取消"]; self.customSearchBar.tintColor = [UIColor colorWithRed:86/255.0 green:179/255.0 blue:11/255.0 alpha:1]; //修正光标颜色 [searchField setTintColor:[UIColor blackColor]]; //其中fm_setCancelButtonTitle是我写的UISearchBar一个分类的方法 - (void)fm_setCancelButtonTitle:(NSString *)title { if (IS_IOS9) { [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTitle:title]; }else { [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitle:title]; } }
4. 设置输入框的文字颜色和字体
//4. 设置输入框文字颜色和字体
[self.customSearchBar fm_setTextColor:[UIColor blackColor]];
[self.customSearchBar fm_setTextFont:[UIFont systemFontOfSize:14]];
//下面两个方法是UISearchBar分类代码
- (void)fm_setTextColor:(UIColor *)textColor {
if (IS_IOS9) {
[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]].textColor = textColor;
}else {
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:textColor];
}
}
- (void)fm_setCancelButtonTitle:(NSString *)title {
if (IS_IOS9) {
[[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTitle:title];
}else {
[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitle:title];
}
}
posted on 2016-09-26 17:08 taiyang2014 阅读(181) 评论(0) 编辑 收藏 举报