UISearchController的UISearchBar嵌入在导航栏中:不会成为第一响应者

时间:2017-02-23 10:22:24

标签: ios uinavigationcontroller uisearchbar uisearchcontroller

我正在尝试在我的导航控制器栏的titleView中嵌入一个UISearchController的搜索栏。确切地说,这可以在Apple的UICatalog示例代码中看到并起作用:

// Create the search results view controller and use it for the UISearchController.
AAPLSearchResultsViewController *searchResultsController = [self.storyboard instantiateViewControllerWithIdentifier:AAPLSearchResultsViewControllerStoryboardIdentifier];

// Create the search controller and make it perform the results updating.
self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];
self.searchController.searchResultsUpdater = searchResultsController;
self.searchController.hidesNavigationBarDuringPresentation = NO;

/*
    Configure the search controller's search bar. For more information on how to configure
    search bars, see the "Search Bar" group under "Search".
*/
self.searchController.searchBar.searchBarStyle = UISearchBarStyleMinimal;
self.searchController.searchBar.placeholder = NSLocalizedString(@"Search", nil);

// Include the search bar within the navigation bar.
self.navigationItem.titleView = self.searchController.searchBar;

self.definesPresentationContext = YES;

我尝试对此代码执行相同的操作:

 self.searchSuggestionsController = [[SearchSuggestionsTableViewController alloc]initWithStyle:UITableViewStylePlain];
self.searchSuggestionsController.delegate = self;
self.searchController = [[UISearchController alloc]initWithSearchResultsController:self.searchSuggestionsController];
self.searchController.delegate = self;
self.searchController.searchResultsUpdater =  self.searchSuggestionsController;
self.searchController.searchBar.delegate = self;

self.searchController.dimsBackgroundDuringPresentation = YES;
[self.searchController setHidesNavigationBarDuringPresentation:NO];



self.searchController.searchBar.searchBarStyle = UISearchBarStyleProminent;
[self.searchController.searchBar setPlaceholder:NSLocalizedString(@"Search", nil)];

[self.navigationItem setTitleView:self.searchController.searchBar];

if (self.searchQuery) {
    [self.searchController.searchBar setText:_searchQuery.queryString];
}

self.definesPresentationContext = YES;

但是当我在设备或模拟器中运行它时,导航栏中的搜索栏将永远不会成为第一响应者。键盘没有显示,我无法输入文字。我能做的是使用清除按钮,文字清除但我仍然无法输入任何文本。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

老问题,但只是遇到了类似的问题。一定要嵌入" searchBar"在VC heirachy中的有效导航控制器中。这恰好是我的错误。这样可行;

CCCTestVC *tVC = [[CCCTestVC alloc] init];
UINavigationController *nC = [[UINavigationController alloc] initWithRootViewController:tVC];
[self.navigationController  presentViewController:nC animated:YES completion:nil];

而不是这样做;

CCCTestVC *tVC = [[CCCTestVC alloc] init];
[self.navigationController pushViewController:tVC animated:YES];