iOS8 Cannot hide cancel button on search bar in UISearchController

后端 未结 9 647
后悔当初
后悔当初 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:54

    This was the simplest solution I could come up with in Swift.

    Custom search controller:

    class CustomSearchController: UISearchController {
    
        var _searchBar: CustomSearchBar
    
        override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
            self._searchBar = CustomSearchBar()
            super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        }
    
        override init(searchResultsController: UIViewController?) {
            self._searchBar = CustomSearchBar()
            super.init(searchResultsController: searchResultsController)
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        override var searchBar: UISearchBar {
            return self._searchBar
        }
    }
    

    Custom search bar:

    class CustomSearchBar: UISearchBar {
        override func setShowsCancelButton(showsCancelButton: Bool, animated: Bool) {
            // do nothing
        }
    }
    

    The most important piece of this was to only create the _searchBar object once in init vs. creating it inside of the stored property.

提交回复
热议问题