开发者

Hide/Display searchDisplayController from search NavigationBar button

I would like to hide/display the searchDisplayController from the button (search) located开发者_运维技巧 on the right part of the navigation bar. When user clicks this button, the searchDisplayController is displayed and user can make a search in the tableview. When user clicks this button again, the searchDisplayController is hidden with animation.

How to do this ?


To add search button on navigation bar use this code:

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

and implement following method:

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


It sounds like you already have a handle on adding the search button to the navigation bar, but in case you don't, here is code that can do that:

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

Once you have that in place, you'll need to implement the showSearch: method to actually toggle the search bar's visibility. One key point to consider here is that the UISearchDisplayController is not a view; the UISearchBar that you have configured it with is what's actually showing the search interface. So what you really want to do is toggle visibility of that search bar. The methods below use the search bar view's alpha property to fade it out or in, while at the same time animating the main view's frame to take up (or vacate) the space that was occupied by the search bar.

- (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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜