[iOS学习]搜索框(UISearchController)最近踩过的坑

坑点一:新页面回跳,searchBar有闪烁现象

解决思路:猜测应该是searchBar呈现过程中,颜色变换造成的闪烁

解决方案:去除searchBar中的中间层的UIView(查资料所得,具体地址未记录,原作者请见谅)

代码:

for (UIView *view in self.searchController.searchBar.subviews) {.
    //self.searchController.searchBar 更改为自己的searchBar
    // for later iOS7.0(include)
    if ([view isKindOfClass:NSClassFromString(@"UIView")] && view.subviews.count > 0) {
        [[view.subviews objectAtIndex:0] removeFromSuperview];
        break;
    }
}

坑点二:跳转到新页面使searchBar成为第一响应者的时间点问题

解决思路:延迟设置,使searchBar必定能成为第一响应者

解决方案:当页面出现后再延迟设置(来自ios - Cannot set searchBar as firstResponder - Stack Overflow)

代码:

- (void)viewDidAppear:(BOOL)animated {
       [super viewDidAppear:animated];
       [self performSelector:@selector(showKeyboard) withObject:nil afterDelay:0];
}

- (void)showKeyboard {
       [self.searchController.searchBar becomeFirstResponder];
}

坑点三:UISearchController中的searchBar的cancel按钮问题

需求方案一:修改cancel按钮文字,监听按钮点击事件

效果:自带的cancel按钮点击后会消失,编辑时又出现,个人感觉不怎么样

来源:CocoaChina上的某一篇问答中,具体未查找到,请原作者勿怪

代码:

self.searchController.searchBar.showsCancelButton = YES;  //这个必须设置,不然无法达到效果,具体原因未知(猜测是需要设置显示才能拿到按钮)

UIButton *canceLBtn = [self.searchController.searchBar valueForKey:@"cancelButton"];

[canceLBtn setTitle:@"搜索" forState:UIControlStateNormal];

[canceLBtn setTitleColor:[UIColor colorWithRed:0.965 green:0.290 blue:0.608 alpha:1.00] forState:UIControlStateNormal];  //设置颜色自便,也可添加点击事件响应

需求方案二:隐藏cancel按钮,自己写按钮
效果:效果挺不错,看着舒服多了
来源:ios - iOS8 Cannot hide cancel button on search bar in UISearchController - Stack Overflow

代码:

// 重写UISearchController中的代理方法,设置不显示cancelBtn
// 我尝试过很多地方写隐藏cancel,不过只有这边管用,应该这边触发的最晚,所以成功了
- (void)didPresentSearchController:(UISearchController *)searchController {
    searchController.searchBar.showsCancelButton = NO;
}

原作者:Orangebb
链接:http://www.jianshu.com/p/5a2f6126508f

你可能感兴趣的:(Objective-C)