UISearchController searchBar showsCancelButton没有受到尊重

Kyl*_*cot 15 xcode ios swift

我已经在我的应用程序中添加了一个UISearchController,并将它的searchBar设置titleView为我的navigationItem.

这有效,但我看到了取消按钮,尽管设置showsCancelButtonfalse.

    searchController = UISearchController(searchResultsController: searchResultsController)
    searchController.searchResultsUpdater = searchResultsUpdater


    // Configure the searchBar
    searchController.searchBar.placeholder = "Find Friends..."
    searchController.searchBar.sizeToFit()
    searchController.searchBar.showsCancelButton = false

    self.definesPresentationContext = true

    navigationItem.titleView = searchController.searchBar
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

pba*_*sdf 10

我同意,这似乎是一个错误.问题是searchController不断重置showsCancelButtonsearchBar 的属性.我找到了一个解决方案,涉及:

  1. 子类化UISearchBar忽略setShowsCancelButton.
  2. 要使searchController使用该子类,必须使用子类UISearchController.
  3. 然后你发现searchBar没有触发搜索控制器的委托方法,所以你必须单独触发它们......

令人费解,但它似乎做了伎俩.你可以在这里找到完整的答案.


Kyl*_*cot 8

这似乎是iOS中的一个错误.我所描述的相同行为可以在Apple提供的示例项目中看到

https://developer.apple.com/library/ios/samplecode/TableSearch_UISearchController/Introduction/Intro.html

文档说明了默认值,NO但似乎并非如此.设置showsCancelButtonNO似乎没有任何效果.

我为此提出了雷达,我正等着收听.


Vit*_*pov 6

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
    }
}}
Run Code Online (Sandbox Code Playgroud)

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

    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
})()
Run Code Online (Sandbox Code Playgroud)