如何显示和隐藏UISearchDisplayController的UISearchBar

时间:2013-12-15 07:51:08

标签: objective-c uinavigationbar uisearchbar uisearchdisplaycontroller

我有一个位于导航右侧的按钮搜索。 这是我的代码:

UIButton *btnSearch = [UIButton buttonWithType:UIButtonTypeCustom];
btnSearch.frame = CGRectMake(0, 0, 22, 22);
[btnSearch setImage:[UIImage imageNamed:@"search_btn.png"] forState:UIControlStateNormal];
[btnSearch addTarget:self action:@selector(showSearch:) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithCustomView:_btnSearch];

self.navigationItem.rightBarButtonItems = searchItem ;

这就是它的样子。
enter image description here

我想在点击搜索按钮后显示搜索栏,点击取消后关闭它然后再显示导航栏,但我不知道如何编码。

- (IBAction)showSearch:(id)sender{
    ???
}

这就是我想要的。 enter image description here

请帮助或提供一些示例代码。我真的需要它。

感谢阅读。

1 个答案:

答案 0 :(得分:4)

将属性UISearchBar *mySearchBar添加到viewController中

@property(nonatomic, retain) UISearchBar *mySearchBar;

符合UISearchBarDelegate

@interface HomeViewController () <UISearchBarDelegate>
...
...
@end

然后将showSearch方法实现为

-(void)showSearch:(id)sender {
if(!mySearchBar) {
    mySearchBar = [[UISearchBar alloc] init];
    [mySearchBar setFrame:CGRectMake(0, 0, self.view.frame.size.width, 55)];
    [mySearchBar setShowsCancelButton:YES animated:YES];
    [self.view addSubview: mySearchBar];
    mySearchBar.delegate = self;
    self.navigationController.navigationBarHidden = YES;
}else {
    searchBar.alpha = 1.0;
    self.navigationController.navigationBarHidden = YES;
}

然后将搜索栏委托方法实现为:

 - (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar {
        self.navigationController.navigationBarHidden = NO;
        [mySearchBar setAlpha:0.0];
    }

希望你能做到这一点。您也可以直接将其添加到导航控制器本身,如果您需要&amp;然后单独显示/隐藏searchBar

您只需初始化mysearchBar&amp;将其添加到navigationBar as:

   UIBarButtonItem *searchBarItem = [[UIBarButtonItem alloc] initWithCustomView:mySearchBar];
   self.navigationItem.rightBarButtonItem = searchBarItem;