1

我有一個位於導航右側的按鈕搜索。 這是我的代碼:如何顯示和隱藏UISearchDisplayController的UISearchBar

UIButton *btnSearch = [UIButton buttonWithType:UIButtonTypeCustom]; 
btnSearch.frame = CGRectMake(0, 0, 22, 22); 
[btnSearch setImage:[UIImage imageNamed:@"search_btn.png"] forState:UIControlStateNormal]; 
[btnSearch addTarget:self action:@selector(showSearch:) forControlEvents:UIControlEventTouchUpInside]; 

UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithCustomView:_btnSearch]; 

self.navigationItem.rightBarButtonItems = searchItem ; 

這就是它的樣子。
enter image description here

我想顯示點擊搜索按鈕後,搜索欄,並關閉它點擊取消後,然後顯示導航欄回來了,但我不知道如何編寫它。

- (IBAction)showSearch:(id)sender{ 
    ??? 
} 

這就是我想要的。 enter image description here

請幫忙或提供一些示例代碼。我真的需要它。

感謝您的閱讀。

回答

4

添加屬性UISearchBar *mySearchBar到您的viewController作爲

@property(nonatomic, retain) UISearchBar *mySearchBar;

順應UISearchBarDelegate作爲

@interface HomeViewController() <UISearchBarDelegate> 
... 
... 
@end 

然後實現showSearch方法

-(void)showSearch:(id)sender { 
if(!mySearchBar) { 
    mySearchBar = [[UISearchBar alloc] init]; 
    [mySearchBar setFrame:CGRectMake(0, 0, self.view.frame.size.width, 55)]; 
    [mySearchBar setShowsCancelButton:YES animated:YES]; 
    [self.view addSubview: mySearchBar]; 
    mySearchBar.delegate = self; 
    self.navigationController.navigationBarHidden = YES; 
}else { 
    searchBar.alpha = 1.0; 
    self.navigationController.navigationBarHidden = YES; 
} 

然後執行搜索欄代表方法爲:

- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar { 
     self.navigationController.navigationBarHidden = NO; 
     [mySearchBar setAlpha:0.0]; 
    } 

希望你有這樣做的想法。如果你想&然後單獨顯示/隱藏searchBar,你也可以直接將它添加到導航控制器本身。

您可以將其添加到導航控制器只是初始化mysearchBar &其添加到navigationBar爲:

UIBarButtonItem *searchBarItem = [[UIBarButtonItem alloc] initWithCustomView:mySearchBar]; 
    self.navigationItem.rightBarButtonItem = searchBarItem; 
+0

太謝謝你了。現在是工作。 但是,如何使它成爲響應者,這樣我就不必點擊文本框搜索。我的意思是當用戶點擊導航欄中的搜索按鈕,然後顯示文本框搜索內閃爍的光標mySearchbar! 感謝^^ –

+0

您必須告訴系統您希望您的搜索欄成爲第一響應者。因此,只要將代碼行添加到您要顯示搜索欄的代碼中即可。在上面的代碼中,你可以在if-else塊之後添加它。 (或者將其添加到if和else塊中)。 '[mySearchBar becomeFirstResponder];' –

+0

Search cancel button is working good。當點擊取消按鈕時,它將隱藏搜索欄,然後顯示導航欄。 如何通過不點擊取消按鈕來退出搜索欄?我的意思是即使用戶點擊了文本框搜索的一面(如結果列表)。 感謝 –