首页 > 代码库 > ios7 关于searchbar上设置cancelButton的title属性
ios7 关于searchbar上设置cancelButton的title属性
通过 [searchBarsetShowsCancelButton:YES];设置之后默认是“cancel”,想改为中文的
在stackoverflow上参考了很多方法都没用
这里的关键是要获取到 searchbar中得 cancelButton
通过打印 [searchbar subviews]
得到结果如下
(lldb) po [searchBar subviews]
<__NSArrayM 0xd6b0db0>(
<UIView: 0xd6aab30; frame = (0 0; 240 24); clipsToBounds = YES; autoresize =
+H; layer = <CALayer: 0xd6aab90>>
)
也就是其只有一个subview,在stackoverflow上得到些其实
这个cancelbutton在更深一层
打印
[[[searchBar subviews] objectAtIndex:0] subviews]
得到结果:
(lldb) po [[[searchBar subviews] objectAtIndex:0] subviews]
<__NSArrayM 0xd6b0dd0>(
<UISearchBarBackground: 0xd6ab370; frame = (0 0; 240 24); opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0xd6ab4c0>>,
<UINavigationButton: 0xd6abef0; frame = (0 0; 54 30); opaque = NO; layer = <CALayer: 0xd6ac020>>,
<UISearchBarTextField: 0xd6acbe0; frame = (0 0; 0 0); text = ‘‘; clipsToBounds = YES; opaque = NO; layer = <CALayer: 0xd6acdf0>>
)
也就是这个UINavigationButton,对它进行设置
代码如下
searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 240, 24)]; //导航条的搜索条 searchBar.delegate = self; [searchBar setShowsCancelButton:YES]; [searchBar setTintColor:[UIColor blackColor]]; [searchBar setBarTintColor:[UIColor clearColor]]; [searchBar setPlaceholder:@"搜索剧集"]; for(UIView *view in [[[searchBar subviews] objectAtIndex:0] subviews]) { if([view isKindOfClass:[NSClassFromString(@"UINavigationButton") class]]) { UIButton * cancel =(UIButton *)view; [cancel setTitle:@"取消" forState:UIControlStateNormal]; [cancel setTintColor:[UIColor blackColor]]; [cancel.titleLabel setTextColor:[UIColor blackColor]]; } }