基本属性
- barStyle
UIBarStyleDefault
UIBarStyleBlack
UIBarStyleBlackOpaque
UIBarStyleBlackTranslucent
-
placeholder:占位字符
-
prompt:标题
-
tintColor:光标颜色
- 设置背景图片
[searchBar setBackgroundImage:[UIImage imageNamed:@"infocollectClickImage"]];
- 设置搜索框的背景图片
[searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"infocollectClickImage"] forState:UIControlStateNormal];
-
searchBar.showsSearchResultsButton = YES;
- 取消按钮
searchBar.showsCancelButton = YES;
[searchBar setShowsCancelButton:YES animated:YES];
- 搜索框内的图片
[searchBar setImage:[UIImage imageNamed:@"search-search-icon"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
设置cancel/取消按钮
1.利用系统的运行时(Runtime)机制设置:
UIButton *btn = [[UIButton alloc] init];
btn.titleLabel.textAlignment = NSTextAlignmentCenter;
[btn setTitle:@"123" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[searchBar setValue:btn forKeyPath:@"cancelButton"];
运行结果:达不到需求,需要调整按钮和搜索框的位置;
2.遍历UISearchBar的子控件,设置里面的button;
[searchBar setShowsCancelButton:YES animated:YES];
for ( id searchView in [[[searchBar subviews] lastObject]subviews])
{
YANLog(@"%@",[searchView class]);
if ([[searchView class] isSubclassOfClass: NSClassFromString(@"UINavigationButton")]) {
YANLog(@"%@",[searchView class]);
UIButton *cancelBtn = (UIButton *)searchView;
//[cancelBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[cancelBtn setTitle:nil forState:UIControlStateNormal];
[cancelBtn setBackgroundImage:[UIImage imageNamed:@"AppIcon29x29"] forState:UIControlStateNormal];
}
}
该方法如果设置title,设置titleColor与BackgroundImage将失效;字体的颜色将显示为系统的默认颜色;
-
所以该方法只适合设置按钮的颜色和背景图片;文字只能显示cancel或者取消;
-
可以将项目配置设置为支持中文,字体将显示为取消;
注意点:
显示cancel按钮的方法要写在自定义按钮方法前面
3.利用appearance
设置:
该方法不仅可以设置文字、颜色,还可以设置字体大小;
NSMutableDictionary *attr = [NSMutableDictionary dictionary];
attr[NSFontAttributeName] = [UIFont systemFontOfSize:13];
attr[NSForegroundColorAttributeName] = [UIColor redColor];
[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class] , nil] setTitle:@"N"];
[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitleTextAttributes:attr forState:UIControlStateNormal];
运行结果:
注意点:
补充:
方法2与方法3基本可以满足需求;若修改太多,可以Textfile与button自定义一个搜索框;
而且方法2与3可以结合使用: