Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you dismiss a UISearchController ? (iOS 8 and follow)

This must be trivial, but I can't find how you're supposed to dismiss a UISearchController programmatically?

Note that it's the new UISearchController (introduced in 2014 with iOS 8), not the UISearchDisplayController.

So far here's what I've got

// Dismiss the search tableview
searchController.dismissViewControllerAnimated()
// Clear the Search bar text
searchController.active = false

But I still have the cancel button and can't get rid of it.

like image 879
Arnaud Avatar asked Feb 10 '15 17:02

Arnaud


Video Answer


4 Answers

OK so after more testing, turns out you just have to set:

searchController.active = false
// or swift 4+
searchController.isActive = false

This is the first thing I tried but I called it in one of the UISearchControllerDelegate methods which didn't work (probably should have called it with dispatch_async (halbano's answer seems to confirm that)).

Anyway, since I couldn't find that answer online, I'm answering my own question, I hope that it'll help someone.

like image 116
Arnaud Avatar answered Oct 22 '22 15:10

Arnaud


Did you have this problem when you try to dismiss search controller after segueing to another view? I have encountered this problem too. I think you might want to use

self.definesPresentationContext = true 

in the view controller that presents the UISearchController as per this post UISearchController not dismissed when View is pushed. It works for me.

like image 28
Yaoyu Yang Avatar answered Oct 22 '22 15:10

Yaoyu Yang


I was presenting the mine embed on a navigation bar. The code that works for me was:

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.searchController setActive:NO];
        self.navigationController.navigationBar.topItem.title = @"MYTITLE".uppercaseString;
        self.navigationItem.titleView = nil;
    });
}

Hope it helps someone.

like image 11
halbano Avatar answered Oct 22 '22 17:10

halbano


SWIFT 4+

searchController.isActive = false
like image 7
Boris Nikolic Avatar answered Oct 22 '22 17:10

Boris Nikolic