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

百般思念 提交于 2019-12-11 06:19:57

问题


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

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.

  • On the first tap on the button, the searchBar loses its focus and the keyboard hides (as if [searchBar resignFirstResponder] had been called);
  • On the second tap, the view controller is finally being dismissed.

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


回答1:


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



回答2:


In my case, work around is:

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

then you can dismiss viewController by delegate or directly.




回答3:


In my scenario I have a UITableViewController with a search bar as overlay. The search results are in a separate UITableViewController. Now I wanted to dismiss the overlay while the search results are shown. @Guillaume Algis your solution worked perfectly for me as well.

Syntax in Swift 4:

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



回答4:


Swift 4.2

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


来源:https://stackoverflow.com/questions/46585175/how-to-dismiss-a-viewcontroller-while-the-navigationitems-searchbar-has-focus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!