UISearchController searchBar showsCancelButton not being respected

后端 未结 12 2324
北荒
北荒 2021-02-13 03:58

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 t

12条回答
  •  别那么骄傲
    2021-02-13 04:16

    Easy solution in Swift3 - we need to make CustomSearchBar without cancel button and then override the corresponding property in new CustomSearchController:

    class CustomSearchBar: UISearchBar {
    
    override func setShowsCancelButton(_ showsCancelButton: Bool, animated: Bool) {
        super.setShowsCancelButton(false, animated: false)
    }}
    
    
    class CustomSearchController: UISearchController {
    
    lazy var _searchBar: CustomSearchBar = {
        [unowned self] in
        let customSearchBar = CustomSearchBar(frame: CGRect.zero)
        return customSearchBar
        }()
    
    override var searchBar: UISearchBar {
        get {
            return _searchBar
        }
    }}
    

    In MyViewController I initialize and configure searchController using this new custom subclass:

        var mySearchController: UISearchController = ({
        // Display search results in a separate view controller
        //        let storyBoard = UIStoryboard(name: "Main", bundle: Bundle.main)
        //        let alternateController = storyBoard.instantiateViewController(withIdentifier: "aTV") as! AlternateTableViewController
        //        let controller = UISearchController(searchResultsController: alternateController)
        let controller = CustomSearchController(searchResultsController: nil)
        controller.searchBar.placeholder = NSLocalizedString("Enter keyword (e.g. iceland)", comment: "")
        controller.hidesNavigationBarDuringPresentation = false
        controller.dimsBackgroundDuringPresentation = false
        controller.searchBar.searchBarStyle = .minimal
        controller.searchBar.sizeToFit()
        return controller
    })()
    

提交回复
热议问题