基本屬性
- barStyle
UIBarStyleDefault
UIBarStyleBlack
UIBarStyleBlackOpaque
UIBarStyleBlackTranslucent
-
placeholder:占位字符
-
prompt:標題
-
tintColor:光標顏色
- 設(shè)置背景圖片
[searchBar setBackgroundImage:[UIImage imageNamed:@"infocollectClickImage"]];
- 設(shè)置搜索框的背景圖片
[searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"infocollectClickImage"] forState:UIControlStateNormal];
-
searchBar.showsSearchResultsButton = YES;
- 取消按鈕
searchBar.showsCancelButton = YES;
[searchBar setShowsCancelButton:YES animated:YES];
- 搜索框內(nèi)的圖片
[searchBar setImage:[UIImage imageNamed:@"search-search-icon"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
設(shè)置cancel/取消按鈕
1.利用系統(tǒng)的運行時(Runtime)機制設(shè)置:
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"];
運行結(jié)果:達不到需求隶症,需要調(diào)整按鈕和搜索框的位置;
2.遍歷UISearchBar的子控件,設(shè)置里面的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];
}
}
該方法如果設(shè)置title诸衔,設(shè)置titleColor與BackgroundImage將失效;字體的顏色將顯示為系統(tǒng)的默認顏色岂丘;
-
所以該方法只適合設(shè)置按鈕的顏色和背景圖片竞阐;文字只能顯示cancel或者取消;
-
可以將項目配置設(shè)置為支持中文,字體將顯示為取消硫椰;
項目配置方法
項目配置方法
注意點:
顯示cancel按鈕的方法要寫在自定義按鈕方法前面
3.利用appearance
設(shè)置:
該方法不僅可以設(shè)置文字繁调、顏色萨蚕,還可以設(shè)置字體大小;
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];
運行結(jié)果:
注意點:
補充:
方法2與方法3基本可以滿足需求;若修改太多蹄胰,可以Textfile與button自定義一個搜索框岳遥;
而且方法2與3可以結(jié)合使用: