Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS8 Cannot hide cancel button on search bar in UISearchController

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

    ...
like image 705
dguastaf Avatar asked Nov 05 '14 23:11

dguastaf


3 Answers

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.

like image 169
nunofmendes Avatar answered Nov 17 '22 22:11

nunofmendes


For iOS 8, and UISearchController, use this delegate method from UISearchControllerDelegate:

func didPresentSearchController(searchController: UISearchController) {
  searchController.searchBar.showsCancelButton = false
}

Don't forget to set yourself as the delegate: searchController.delegate = self

like image 17
Andrew Robinson Avatar answered Nov 17 '22 22:11

Andrew Robinson


Simply subclass UISearchController & UISearchBar.

class NoCancelButtonSearchController: UISearchController {
    let noCancelButtonSearchBar = NoCancelButtonSearchBar()
    override var searchBar: UISearchBar { return noCancelButtonSearchBar }
}

class NoCancelButtonSearchBar: UISearchBar {
    override func setShowsCancelButton(_ showsCancelButton: Bool, animated: Bool) { /* void */ }
}
like image 15
ma11hew28 Avatar answered Nov 17 '22 23:11

ma11hew28