首页 > 代码库 > 美团HD(7)-添加取消搜索按钮

美团HD(7)-添加取消搜索按钮

DJSelectCityViewController.m

#pragma mark - UISearchBar 代理方法/** SearchBar开始编辑 */- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {    // 隐藏导航栏    [self.navigationController setNavigationBarHidden:YES animated:YES];    // 显示遮罩    UIView *cover = [[UIView alloc] init];    cover.backgroundColor = [UIColor blackColor];    cover.alpha = 0.2;    cover.frame = self.cityTableView.frame;    cover.tag = DJCoverTag;        // 由于UIView 不是UIControl,所以没有addTarget方法,可以使用UITapGestureRecognizer代替    // 当conver被点击时,移除第一响应者    [cover addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:searchBar action:@selector(resignFirstResponder)]];    [self.view addSubview:cover];    // 设置当前搜索框背景为高亮背景    [searchBar setBackgroundImage:[UIImage imageNamed:@"bg_login_textfield_hl"]];    // 显示取消按钮    [searchBar setShowsCancelButton:YES animated:YES];    }/** SearchBar结束编辑 */- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {    // 显示导航栏    [self.navigationController setNavigationBarHidden:NO animated:YES];    // 隐藏遮罩    [[self.view viewWithTag:DJCoverTag] removeFromSuperview];    // 设置当前搜索框背景为普通背景    [searchBar setBackgroundImage:[UIImage imageNamed:@"bg_login_textfield"]];    // 隐藏取消按钮    [searchBar setShowsCancelButton:NO animated:YES];    }/** 当searchBar上面的取消按钮被点击时调用此方法 */- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {    // 隐藏键盘    [searchBar resignFirstResponder];    // 清空输入内容    searchBar.text = @"";}/** 当searchBar内的文字发生改变时调用此方法 */- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {    UIView *cover = [self.view viewWithTag:DJCoverTag];    if (searchText.length) { // 当前输入内容不为空        if(cover.subviews.count <= 0) {            cover.alpha = 1.0;            self.searchResultVC.view.frame = CGRectMake(0, 0, cover.width, cover.height);            [cover addSubview:self.searchResultVC.view];        }    } else { // 当前输入内容为空        [self.searchResultVC.view removeFromSuperview];         cover.alpha = 0.2;    }    }

技术分享

 

美团HD(7)-添加取消搜索按钮