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能够修改她还不知道。
相关文章推荐
- flex 控件的重要属性
- 学习Winform文本类控件(Label、Button、TextBox)
- Delphi控件ListView的属性及使用方法详解
- web下载的ActiveX控件自动更新
- WinForm实现按名称递归查找控件的方法
- C#中父窗口和子窗口之间控件互操作实例
- Android编程之Button控件用法实例分析
- Android控件之CheckBox、RadioButton用法实例分析
- 在Android开发中使用自定义组合控件的例子
- 一款超酷的Android自定义加载控件
- Android重写View实现全新的控件
- MFC中动态创建控件以及事件响应实现方法
- WinForm自定义函数FindControl实现按名称查找控件
- Android控件之ProgressBar用法实例分析
- WinForm拖拽控件生成副本的解决方法
- ASP.NET动态添加用户控件的方法
- ASP.NET的HtmlForm控件学习及Post与Get的区别概述
- WinForm实现移除控件某个事件的方法
- Bootstrap开关(switch)控件学习笔记分享
- laypage分页控件使用实例详解