首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从search NavigationBar隐藏/显示searchDisplayController按钮

从search NavigationBar隐藏/显示searchDisplayController按钮
EN

Stack Overflow用户
提问于 2010-12-09 06:47:53
回答 2查看 1.5K关注 0票数 0

我想通过导航栏右侧的按钮(搜索)隐藏/显示searchDisplayController。当用户单击此按钮时,将显示searchDisplayController,用户可以在表视图中进行搜索。当用户再次单击此按钮时,searchDisplayController将随动画一起隐藏。

该怎么做呢?

EN

回答 2

Stack Overflow用户

发布于 2015-02-24 20:47:43

要在导航栏上添加搜索按钮,请使用以下代码:

代码语言:javascript
复制
 UIBarButtonItem *searchButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(toggleSearch:)];
self.navigationController.navigationBar.topItem.rightBarButtonItem = searchButton;

并实现以下方法:

代码语言:javascript
复制
- (IBAction)toggleSearch:(id)sender
{
    // do something or handle Search Button Action.
}
票数 1
EN

Stack Overflow用户

发布于 2011-01-26 02:48:30

听起来您已经掌握了将搜索按钮添加到导航栏的句柄,但是如果您没有这样做,下面的代码就可以做到这一点:

代码语言:javascript
复制
// perhaps inside viewDidLoad
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
 initWithBarButtonSystemItem:UIBarButtonSystemItemSearch 
 target:self
 action:@selector(showSearch:)] autorelease];

准备就绪后,需要实现showSearch:方法来实际切换搜索栏的可见性。这里需要考虑的一个关键点是,UISearchDisplayController不是一个视图;您用来配置它的UISearchBar才是实际显示搜索界面的对象。因此,您真正想要做是切换搜索栏的可见性。下面的方法使用搜索栏视图的alpha属性将其淡出或淡入,同时使主视图框具有动画效果,以占用(或腾出)搜索栏所占用的空间。

代码语言:javascript
复制
- (void)showSearch:(id)sender {
    // toggle visibility of the search bar
    [self setSearchVisible:(searchBar.alpha != 1.0)];
}

- (void)setSearchVisible:(BOOL)visible {
    // assume searchBar is an instance variable
    UIView *mainView = self.tableView; // set this to whatever your non-searchBar view is
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:UINavigationControllerHideShowBarDuration];
    if (!visible) {
        searchBar.alpha = 0.0;
        CGRect frame = mainView.frame;
        frame.origin.y = 0;
        frame.size.height += searchBar.bounds.size.height;
        mainView.frame = frame;
    } else {
        searchBar.alpha = 1.0;
        CGRect frame = mainView.frame;
        frame.origin.y = searchBar.bounds.size.height;
        frame.size.height -= searchBar.bounds.size.height;
        mainView.frame = frame;
    }
    [UIView commitAnimations];
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4393150

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档