苹果自带的UISearchBar还是蛮好用的,但是在使用过程中也遇到一些坑,比如如何找到searchBar右侧的取消button,以及第一次点击的时候会执行UISearchBar的代理方法:searchBarTextDidBeginEditing 的问题。
首先如何获取cancelButton并且进行自定义呢?
for (UIView *view in [[_searchBar.subviews lastObject] subviews]) {
if ([view isKindOfClass:[UIButton class]]) {
UIButton *cancelBtn = (UIButton *)view;
cancelBtn.enabled = YES;
[cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
[cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[cancelBtn addTarget:self action:@selector(cancelButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
}
}
上面这是复杂一点的方式,下面用更简单的方式获取,那就是利用kvo原理:
UIButton *cancelBtn = [_searchBar valueForKeyPath:@"cancelButton"];
cancelBtn.enabled = YES;
[cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
[cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[cancelBtn addTarget:self action:@selector(cancelButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
大家可能注意到,其中有一行代码 cancelBtn.enabled = YES; 为什么要写这句代码呢?是因为searchBar加载出来以后右侧的取消按钮是默认enabled = NO,所以才会出现点击的时候执行searchBarTextDidBeginEditing方法。注意一点,在搜索完成,searchBar失去焦点的地方,也需要获取到cancelBtn并且设置 cancelBtn.enabled = YES;
比如在点击键盘上的搜索按钮:
//键盘上搜索按钮被点击
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];
UIButton *cancelBtn = [searchBar valueForKeyPath:@"cancelButton"]; //首先取出cancelBtn
cancelBtn.enabled = YES;
}
这样点击取消按钮就会直接退出搜索页面,而不是执行searchBarTextDidBeginEditing方法。
希望以上内容对你有帮助!