从搜索导航栏按钮隐藏/显示searchDisplayController

时间:2010-12-08 22:47:53

标签: iphone ios4

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

怎么做?

2 个答案:

答案 0 :(得分:1)

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

 UIBarButtonItem *searchButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(toggleSearch:)];
self.navigationController.navigationBar.topItem.rightBarButtonItem = searchButton;

并实施以下方法:

- (IBAction)toggleSearch:(id)sender
{
    // do something or handle Search Button Action.
}

答案 1 :(得分:0)

听起来你已经掌握了将搜索按钮添加到导航栏的方法,但如果你没有,这里有代码可以做到这一点:

// perhaps inside viewDidLoad
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
 initWithBarButtonSystemItem:UIBarButtonSystemItemSearch 
 target:self
 action:@selector(showSearch:)] autorelease];

一旦你有了这个,你需要实现showSearch:方法来实际切换搜索栏的可见性。这里要考虑的一个关键点是UISearchDisplayController不是视图;你配置它的UISearchBar实际上是显示搜索界面的。所以你真正想做的是切换该搜索栏的可见性。下面的方法使用搜索栏视图的alpha属性将其淡出或淡入,同时为主视图的框架设置动画以占用(或腾出)搜索栏占用的空间。

- (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];
}
相关问题