有很多示例代码可供参考,我认为我按照它的每一行来编写我的代码:
(void)viewDidLoad
{
[super viewDidLoad];
// init search bar
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
searchBar.delegate = self;
searchBar.showsCancelButton=YES;
// set up searchDisplayController
UISearchDisplayController *searchController = [[UISearchDisplayController alloc]
initWithSearchBar:searchBar contentsController:self];
searchController.delegate = self;
searchController.searchResultsDataSource = self;
searchController.searchResultsDelegate = self;
// display search bar in nav bar
self.searchDisplayController.displaysSearchBarInNavigationBar = YES;
}
使用上述代码,我应该在导航栏中看到搜索栏的显示吗?但是我只看到取消按钮。我已在头文件中声明了协议
<UISearchDisplayDelegate, UISearchBarDelegate>
,我错过了什么或出了什么问题?谢谢。注意:使用
self.navigationItem.titleView = searchBar
,搜索栏会按预期显示。我不知道新的displaysSearchBarInNavigationBar
方法有什么优点。--由tassilo编辑--
看起来搜索栏被添加到导航栏,但随后消失了。
图片链接: https://istack.dev59.com/a3fND.webp https://istack.dev59.com/YNTko.webp