iOS8 Cannot hide cancel button on search bar in UISearchController

后端 未结 9 551
后悔当初
后悔当初 2021-01-01 12:26

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

相关标签:
9条回答
  • 2021-01-01 12:34

    Swift:

    The following worked for me, added under viewDidLoad, because I never wanted that button:

    let searchBarStyle = searchBar.value(forKey: "searchField") as? UITextField
    searchBarStyle?.clearButtonMode = .never
    

    Make sure to add the ID for the searchBar in the storyboard.

    0 讨论(0)
  • 2021-01-01 12:37

    Use UISearchControllerDelegate.

    func willPresentSearchController(_ searchController: UISearchController) {
    
            searchController.searchBar.setValue("", forKey:"_cancelButtonText")
        }
    
    0 讨论(0)
  • 2021-01-01 12:40

    The following github project subclasses UISearchBar which is presented as solution 2:

    https://github.com/mechaman/CustomSearchControllerSwift

    On top of it, it also subclasses UISearchController to enable one to put the search bar in places other than the tableView header!

    Hope this helps.

    0 讨论(0)
  • 2021-01-01 12:42

    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

    0 讨论(0)
  • 2021-01-01 12:47

    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 */ }
    }
    
    0 讨论(0)
  • 2021-01-01 12:50

    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.

    0 讨论(0)
提交回复
热议问题