隐藏UISearchController中搜索栏上的“取消”按钮

时间:2015-10-20 02:52:27

标签: ios swift ios9 uisearchcontroller

我试图隐藏UISearchController中搜索栏的“取消”按钮,但遗憾的是在viewDidLoad()中设置以下内容不起作用:

override func viewDidLoad() {
    super.viewDidLoad()

    searchResultsTableController = UITableViewController()
    searchResultsTableController.tableView.delegate = self

    searchController = UISearchController(searchResultsController: searchResultsTableController)
    searchController.searchResultsUpdater = self
    searchController.searchBar.sizeToFit()
    searchResultsView.tableHeaderView = searchController.searchBar

    searchController.delegate = self
    searchController.dimsBackgroundDuringPresentation = false
    searchController.searchBar.delegate = self

    searchController.searchBar.searchBarStyle = .Minimal
    searchController.searchBar.showsCancelButton = false

    definesPresentationContext = true
}

我也试过在这个委托方法中使用上面的代码:

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

此方法有效但在隐藏之前会短暂显示“取消”按钮,这并不理想。有什么建议吗?

6 个答案:

答案 0 :(得分:25)

我最终按照建议继承了UISearchBarUISearchController

<强> CustomSearchBar.swift

import UIKit

class CustomSearchBar: UISearchBar {

    override func layoutSubviews() {
        super.layoutSubviews()
        setShowsCancelButton(false, animated: false)
    }
}

<强> CustomSearchController.swift

import UIKit

class CustomSearchController: UISearchController, UISearchBarDelegate {

    lazy var _searchBar: CustomSearchBar = {
        [unowned self] in
        let result = CustomSearchBar(frame: CGRectZero)
        result.delegate = self

        return result
    }()

    override var searchBar: UISearchBar {
        get {
            return _searchBar
        }
    }
}

答案 1 :(得分:1)

隐藏搜索栏委派方法中的“取消”按钮,并设置您的委托searchController.searchBar.delegate=self UISearchBarDelegate

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {

}

func searchBarTextDidEndEditing(searchBar: UISearchBar) {

}

答案 2 :(得分:1)

尝试继承UISearchBar并实施:

override func layoutSubviews() {
   super.layoutSubviews()
   self.setShowsCancelButton(false, animated: false)
}

这个SO thread可以帮助您更多地朝这个方向发展。

答案 3 :(得分:1)

欢喜!从iOS 13开始,可以访问automaticallyShowsCancelButton上的UISearchController。将其设置为false以隐藏“取消”按钮。

答案 4 :(得分:0)

与@Griffith和@Abhinav给出的答案相同,但使用的是扩展名:

extension UISearchBar {
    override open func layoutSubviews() {
        super.layoutSubviews()
        setShowsCancelButton(false, animated: false)
    }
}

此代码来自Swift 4。

答案 5 :(得分:0)

func didPresentSearchController(_ searchController: UISearchController) {
    searchController.searchBar.becomeFirstResponder()
    searchController.searchBar.showsCancelButton = true
}


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

就我而言,上述所有解决方案均有效。您需要在didPresentSearchController中显示并将其隐藏在didDismissSearchController中。早些时候,我只是藏在didDismissSearchController中,该对象在取消时仍显示“取消”按钮。