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

UISearchController's UISearchBar embedded in Navigation Bar: Does not become first responder

我正在尝试将 UISearchController 的搜索栏嵌入到导航控制器栏的 titleView 中。确切地说,这可以在 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;

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

有什么想法吗?

尝试实施 UISearchBarDelegate

并在 searchBarTextDidBeginEditing

中调用 searchBarbecomeFirstResponder()

然后在 searchBarTextDidEndEditing 调用 resignFirstResponder()

老问题,但刚刚遇到了类似的问题。请务必将 "searchBar" 嵌入到 VC 继承权中的有效导航控制器中。那恰好是我的错误。所以这有效;

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];