Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dismissing a modal view controller with Search Bar cancel button

I've got a modal view controller with search bar and tableview, basically a pop-over search-box, presented using a pop-over segue. At the top it has a UISearchBar with a cancel button. I'm trying to dismiss the view controller using the cancel button on that search bar.

I tried quite a few approaches...

-(void) searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

and

[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];

and delegate methods along the lines of

[self.delegate dismissModalViewController:self]

with

-(void) dismissModalViewController:(UIViewController*) viewToDismiss
{
    [viewToDismiss dismissViewControllerAnimated:YES completion:nil];
}

I don't know whether the UISearchBar is interfering but it seemed a reasonable hypothesis. Otherwise this is a common topic and I apologise for asking a question that may well have been answered before but I've read the fm and googled till I'm blue and still no results.

like image 757
Tom Ridd Avatar asked Jun 13 '13 21:06

Tom Ridd


People also ask

How do you dismiss a modal view controller?

According to the View Controller Programming guide for iPhone OS, this is incorrect when it comes to dismissing modal view controllers you should use delegation. So before presenting your modal view make yourself the delegate and then call the delegate from the modal view controller to dismiss.


1 Answers

I experienced the same thing in a UIPopoverPresentationController within which I use a UISearchController to filter a tableview.

The problem is that the first time you call dismissViewController it dismisses the UISearchController, but there are no effects on the UI, so it's easy to think nothing happened. This is the UISearchBar interfering as you mention.

A solution is to call dismissViewController twice (I don't like this), or to call searchController.dismissViewController followed by self.dismissViewController.

Swift 3 example...

if searchController.isActive {
    searchController.dismiss(animated: true, completion: { 
        self.dismiss(animated: true) 
    })
} else {
    dismiss(animated: true)
}
like image 165
Marmoy Avatar answered Sep 23 '22 22:09

Marmoy