我想從位於導航欄右側的按鈕(搜索)中隱藏/顯示searchDisplayController。 當用戶單擊此按鈕時,會顯示searchDisplayController,用戶可以在tableview中進行搜索。 當用戶再次單擊此按鈕時,searchDisplayController將隱藏動畫。從搜索中隱藏/顯示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.
}