无法摆脱取消按钮

时间:2014-12-16 15:54:09

标签: ios uisearchdisplaycontroller

我正在使用搜索显示控制器,在某些情况下我不需要取消按钮

尚在searchBarShouldBeginEditing设置showsCancelButtonNOsetShowsCancelButton:animated:

无效

我该怎么做才能摆脱按钮?

1 个答案:

答案 0 :(得分:0)

Swift3 中的简单解决方案 - 我们需要使用 CustomSearchBar 而不使用取消按钮,然后覆盖新 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
    }
}}

在MyViewController中,我使用这个新的自定义子类初始化和配置searchController:

    var videoSearchController: 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
})()

它工作正常且顺畅! : - )