75

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.

Arnaud
  • 17,268
  • 9
  • 65
  • 83

5 Answers5

186

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.

Arnaud
  • 17,268
  • 9
  • 65
  • 83
24

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.

Community
  • 1
  • 1
Yaoyu Yang
  • 396
  • 2
  • 7
11

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.

halbano
  • 1,135
  • 14
  • 34
  • 3
    wasnt the exact code, but the dispatch async pointed me in the right direction! – kennydust Jan 04 '16 at 05:15
  • Good! Also get the main thread to handle UI elements is mandatory, maybe this was the magic. – halbano Jan 04 '16 at 17:21
  • 2
    @halbano this delegate method is called on the main thread. I believe there's crosstalk between the search bar animation and whatever the listener is doing here that is the cause of conflict. this will perform the responding code on the next run loop. – Stephen Paul Sep 07 '18 at 19:29
7

SWIFT 4+

searchController.isActive = false
Boris Nikolic
  • 746
  • 14
  • 24
1

I had this problem using the search and interactionController, solved after just include the line: self.dismissViewControllerAnimated(false, completion: nil)

Open the interaction and clear the search without changes in the delegate.

MSamsoniuk
  • 19
  • 4
  • 1
    The problem is this won't trigger some delegate functions like `willDismissSearchController` which could be necessary. – aasatt Jan 05 '18 at 00:17