从搜索中隐藏/显示searchDisplayController导航栏按钮
问题描述:
我想从位于导航栏右侧的按钮(搜索)中隐藏/显示searchDisplayController。 当用户单击此按钮时,会显示searchDisplayController,用户可以在tableview中进行搜索。 当用户再次单击此按钮时,searchDisplayController将隐藏动画。从搜索中隐藏/显示searchDisplayController导航栏按钮
如何做到这一点?
答
这听起来像你已经有了将该搜索按钮,导航栏的把手,但如果你不这样做,这里是代码,可以做到这一点:
// 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];
}
答
要添加搜索按钮导航栏上使用此代码:
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.
}