Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISearchController searchBar showsCancelButton not being respected

Tags:

xcode

ios

swift

I've added a UISearchController to my application and set it's searchBar to the titleView of my navigationItem.

This works but I am seeing the cancel button despite having set showsCancelButton to false.

    searchController = UISearchController(searchResultsController: searchResultsController)
    searchController.searchResultsUpdater = searchResultsUpdater


    // Configure the searchBar
    searchController.searchBar.placeholder = "Find Friends..."
    searchController.searchBar.sizeToFit()
    searchController.searchBar.showsCancelButton = false

    self.definesPresentationContext = true

    navigationItem.titleView = searchController.searchBar

enter image description here

like image 739
Kyle Decot Avatar asked Apr 30 '15 19:04

Kyle Decot


1 Answers

I agree, it seems like a bug. The problem is that the searchController keeps resetting the showsCancelButton property of the searchBar. I found a solution that involves:

  1. subclassing UISearchBar to ignore setShowsCancelButton.
  2. to make the searchController use that subclass, you have to subclass UISearchController.
  3. And then you find that the searchBar is not triggering the search controller's delegate methods, so you have to trigger them separately...

Convoluted, but it seems to do the trick. You can find the full answer here.

like image 180
pbasdf Avatar answered Oct 19 '22 09:10

pbasdf