您的位置:首页 > 产品设计 > UI/UE

iOS 修改UISearchBar cancel 按钮

2016-06-07 11:53 537 查看

修改UISearchBar cancel 按钮

最近做一个UISearchController的搜索功能,可是UISearchBar的取消按钮标题为“cancel”,想要修改为“取消”,参考了许多东西,大都是要遍历UISearchBar的子控件,找到类型为“UIButton”或子控件的父类是“UIButton”的子控件,通过UIButton的方法来修改它的标题或颜色。

例如:

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
// iOS 7.0+ for (id view in [self.subviews[0] subviews]) {
// iOS 7.0- for (id view in self.subviews) {
for (id view in [self.subviews[0] subviews]) {
if ([view isKindOfClass:[UIButton class]]) {
UIButton *button = (UIButton *)view;
[button setTitle:title forState:UIControlStateNormal];
break;
}
}
}


但这样不够完美,当App启动后第一次点击搜索框输入内容搜索时,“cancel”按钮的标题是不会改变的,只有取消后再次编辑才会改变。原因是在
searchBarTextDidBeginEditing:
方法中执行修改的时候UISearchBar的子控件或子控件的子控件中还没有UIButton类型的控件,因为不好把握“cancel”按钮加入到searchBar中的时机,所以“cancel”按钮的修改不太完美。

后来查找了很多方法,发现两句代码就搞定了:

[[UIBarButtonItem appearanceWhenContainedIn: [UISearchBar class], nil] setTintColor:[UIColor whiteColor]];
[[UIBarButtonItem appearanceWhenContainedIn: [UISearchBar class], nil] setTitle:@"取消"];


“cancel”按钮在searchBar中是”UINavigationButton”类型的,UINavigationButton的父类是UIButton。为什么UIBarButtonItem的appearance能够修改她还不知道。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  控件