通过 [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,对它进行设置
代码如下
ios6和ios7情况不一样,ios7中searchBar得层级多了一层
if (iOS7) {
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]];
// [cancel setImage:[UIImage imageNamed:@"cancel.png"] forState:UIControlStateNormal];
}
if ([view isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
{
[view removeFromSuperview];
}
}
}else
{
for(UIView *view in [searchBar subviews]) {
if([view isKindOfClass:[NSClassFromString(@"UINavigationButton") class]]) {
UIButton * cancel =(UIButton *)view;
[cancel setTitle:@"取消" forState:UIControlStateNormal];
[cancel setTintColor:[UIColor blackColor]];
[cancel.titleLabel setTextColor:[UIColor blackColor]];
cancel.backgroundColor = [UIColor clearColor];
}
if ([view isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
{
[view removeFromSuperview];
}
}
}
可以通过
(lldb) po [searchBar recursiveDescription] 来查看一下searchBar的视图层级