【问题标题】:How to dismiss a ViewController while the navigationItem's searchBar has focus当 navigationItem 的 searchBar 有焦点时如何关闭 ViewController
【发布时间】:2017-10-05 12:04:13
【问题描述】:

我更新了我的应用以处理导航栏下搜索栏的新 iOS 11 搜索行为:

- (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 失去焦点并且键盘隐藏(就像调用了[searchBar resignFirstResponder]);
  • 在第二次点击时,视图控制器终于被关闭了。

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

【问题讨论】:

    标签: ios uiviewcontroller uisearchcontroller


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      Swift 4 中的语法:

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

      【讨论】:

        【解决方案3】:

        斯威夫特 4.2

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

        【讨论】:

          【解决方案4】:

          就我而言,解决方法是:

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

          然后您可以通过委托或直接关闭 viewController。

          【讨论】:

            【解决方案5】:

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

            以下对我来说解决了这个问题:

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

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2019-04-07
              • 1970-01-01
              • 1970-01-01
              • 2016-09-23
              • 1970-01-01
              • 2018-05-03
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多