iOS8 Cannot hide cancel button on search bar in UISearchController

dguastaf picture dguastaf · Nov 6, 2014 · Viewed 18.1k times · Source

My goal is to prevent the cancel button from appearing in a search bar in a UISearchController. I started with Apple's Table Search with UISearchController sample code and hid the cancel button as seen in the code snip below. However, when the user taps in the text field, the cancel button still appears. Any help?

override func viewDidLoad() {
    super.viewDidLoad()

    resultsTableController = ResultsTableController()

    searchController = UISearchController(searchResultsController: resultsTableController)
    searchController.searchResultsUpdater = self
    searchController.searchBar.sizeToFit()
    tableView.tableHeaderView = searchController.searchBar

    searchController.searchBar.delegate = self

    //Hide cancel button - added by me
    searchController.searchBar.showsCancelButton = false

    ...

Answer

nunofmendes picture nunofmendes · Nov 6, 2014

I think there are three ways of achieving that:

  1. Override searchDisplayControllerDidBeginSearch and use the following code:

searchController.searchBar.showsCancelButton = false

  1. Subclass UISearchBar and override the layoutSubviews to change that var when the system attempts to draw it.

  2. Register for keyboard notification UIKeyboardWillShowNotification and apply the code in point 1.

Of course can always implement your search bar.