Iphone 从搜索导航栏按钮隐藏/显示searchDisplayController
我想通过导航栏右侧的按钮(搜索)隐藏/显示searchDisplayController。 当用户单击此按钮时,将显示searchDisplayController,用户可以在tableview中进行搜索。 当用户再次单击此按钮时,searchDisplayController将隐藏动画Iphone 从搜索导航栏按钮隐藏/显示searchDisplayController,iphone,ios4,Iphone,Ios4,我想通过导航栏右侧的按钮(搜索)隐藏/显示searchDisplayController。 当用户单击此按钮时,将显示searchDisplayController,用户可以在tableview中进行搜索。 当用户再次单击此按钮时,searchDisplayController将隐藏动画 如何做到这一点?听起来您已经掌握了将搜索按钮添加到导航栏的方法,但如果您没有,下面是可以做到这一点的代码: // perhaps inside viewDidLoad self.navigationItem.r
如何做到这一点?听起来您已经掌握了将搜索按钮添加到导航栏的方法,但如果您没有,下面是可以做到这一点的代码:
// perhaps inside viewDidLoad
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemSearch
target:self
action:@selector(showSearch:)] autorelease];
一旦设置好了,就需要实现showSearch:方法来实际切换搜索栏的可见性。这里要考虑的一个关键点是UISEARCHISDISPLAY控制器不是视图;您配置的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];
}
要在导航栏上添加搜索按钮,请使用以下代码:
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.
}