小编典典

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

swift

我试图在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
}

这种方法可行,但是在隐藏它之前会短暂显示“取消”按钮,这是不理想的。有什么建议?


阅读 634

收藏
2020-07-07

共1个答案

小编典典

我最终对这两个子类都进行了子类化,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
        }
    }
}
2020-07-07