如何显示和隐藏UISearchDisplayController的UISearchBar [英] How to Show and Hide UISearchDisplayController's UISearchBar

查看:104
本文介绍了如何显示和隐藏UISearchDisplayController的UISearchBar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在导航的右侧有一个按钮搜索. 这是我的代码:

I have a button search that located in the right side of the navigation. This is my code:

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 ;

这是它的外观.

This is how it's look.

我想在单击搜索按钮后显示搜索栏,在单击取消后将其关闭,然后向后显示导航栏,但是我不知道如何编写代码.

And I want to display search bar after clicked on the search button, and close it after clicked on cancel and then show the Navigationbar back, but I don't know how to code it.

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

这就是我想要的.

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

Please help or provide some sample code. I really need it.

感谢阅读.

推荐答案

将属性UISearchBar *mySearchBar添加为

@property(nonatomic, retain) UISearchBar *mySearchBar;

符合

@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;
}

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

Then implement the search bar delegate method as :

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

希望您能做到这一点.您也可以直接将其直接添加到导航控制器本身.然后玩单独显示/隐藏searchBar".

Hope you have got the idea by doing this. Also you can add it directly to navigation controller, itself, if you want & then play with Showing/ hiding the searchBar alone.

您可以将其添加到导航控制器中,只需初始化mysearchBar&将其添加到navigationBar中:

You can add it to navigation controller as just initialize the mysearchBar & add it to navigationBar as :

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

这篇关于如何显示和隐藏UISearchDisplayController的UISearchBar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆