如何在 navigationItem 的 searchBar 具有焦点时关闭 ViewController [英] How to dismiss a ViewController while the navigationItem's searchBar has focus

查看:19
本文介绍了如何在 navigationItem 的 searchBar 具有焦点时关闭 ViewController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I updated my app to handle the new iOS 11 search behavior for search bars under the navigation bar:

- (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;
}

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

I also have a button on my view, which when tapped will dismiss the current view controller:

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

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

The problem is: if the searchController's searchBar has focus (ie. is the first responder) when the user taps the button, the view controller is not dismissed.

  • 在第一次点击按钮时,searchBar 失去焦点并且键盘隐藏(好像 [searchBar resignFirstResponder] 已被调用);
  • 在第二次点击时,视图控制器终于被解除.

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

How can I make the first tap on the button dismiss the view controller immediately (removing the searchBar's focus as a side effect)?

推荐答案

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

The solution to dismiss the view controller immediately is to use the UISearchController isActive property:

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

这篇关于如何在 navigationItem 的 searchBar 具有焦点时关闭 ViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆