如何在导航项的搜索栏具有焦点时关闭 ViewController

How to dismiss a ViewController while the navigationItem's searchBar has focus

我更新了我的应用程序以处理导航栏下搜索栏的新 iOS11 搜索行为:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UISearchController *searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.navigationItem.searchController = searchController;

    // Those are optional, but that's what I want my UI to look like
    searchController.hidesNavigationBarDuringPresentation = NO;
    searchController.obscuresBackgroundDuringPresentation = NO;
    self.navigationItem.hidesSearchBarWhenScrolling = NO;
}

我的视图上还有一个按钮,点击它会关闭当前视图控制器:

- (IBAction)dismiss:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

问题是:如果当用户点击按钮时 searchController 的 searchBar 有焦点(即第一响应者),视图控制器不会被关闭。

如何让第一次点击按钮时立即关闭视图控制器(作为副作用删除 searchBar 的焦点)?

立即关闭视图控制器的解决方案是使用 UISearchController isActive property:

- (IBAction)dismiss:(id)sender
{
    self.navigationItem.searchController.active = NO;
    [self dismissViewControllerAnimated:YES completion:nil];
}

就我而言,解决方法是:

UIView.setAnimationsEnabled(false)
searchController.isActive = false
UIView.setAnimationsEnabled(true)

那么您可以通过委托或直接解雇viewController。

在我的场景中,我有一个 UITableViewController,其中有一个搜索栏作为覆盖。搜索结果在单独的 UITableViewController 中。现在我想在显示搜索结果时关闭叠加层。 @Guillaume Algis 你的解决方案对我也很有效。

Swift4 中的语法:

    self.navigationItem.searchController?.isActive = false
    self.dismiss(animated: true) {}

Swift 4.2

self.searchController.dismiss(animated: false, completion: nil)
self.dismiss(animated: true, completion: {
   ///
})

以上所有方法都会导致 updateSearchResults 以空字符串调用。
根据您的实施,这可能会导致重新加载 tableview,这可能会损害用户体验。

以下解决方法适用于我:

self.presentingViewController?.dismiss(animated: true, completion: nil)