带有 scopeBar 奇怪行为的 searchBar

searchBar with scopeBar weird behaviour

我遇到了 searchBar 和 scopeBar 的问题。 Bascialy 一旦我单击 "cancel" 并设置 searchBar.showsScopeBar = false,在下次出现 searchBar 时得到这个奇怪的 space。

这里有一些代码:

override func viewDidLoad() {
    super.viewDidLoad()

    self.resultSearchController = ({

        let controller = UISearchController(searchResultsController: nil)

        controller.searchResultsUpdater = self
        controller.dimsBackgroundDuringPresentation = false
        controller.hidesNavigationBarDuringPresentation = true

        controller.searchBar.searchBarStyle = UISearchBarStyle.Minimal

        controller.searchBar.delegate = self
        controller.searchBar.sizeToFit()

        self.tableView.tableHeaderView = controller.searchBar

        return controller
    })()

以及显示和隐藏范围栏背后的逻辑:

func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
    self.resultSearchController.searchBar.showsScopeBar = true
    self.resultSearchController.searchBar.scopeButtonTitles = ["All", "Hot", "Active", "Warm"]
    self.resultSearchController.searchBar.sizeToFit();
    return true
}


func searchBarShouldEndEditing(searchBar: UISearchBar) -> Bool {
    self.resultSearchController.searchBar.showsScopeBar = false
    return true
}

这就是正在发生的事情:

我可以接受始终可见的 scopeBar 栏,但是当创建过程中在 searchBar 之前弹出时,当我详细介绍时,它会落在下面。所以比现在更惨。

您可以在创建 UISearchController 本身的过程中创建范围栏(它仅在搜索栏处于活动状态时可见)。您无需手动显示或隐藏范围栏。

override func viewDidLoad() {
    super.viewDidLoad()

    self.resultSearchController = ({

        let controller = UISearchController(searchResultsController: nil)

        controller.searchResultsUpdater = self
        controller.dimsBackgroundDuringPresentation = false
        controller.hidesNavigationBarDuringPresentation = true

        controller.searchBar.searchBarStyle = UISearchBarStyle.Minimal

        controller.searchBar.delegate = self
        controller.searchBar.sizeToFit()

        controller.searchBar.scopeButtonTitles = ["All", "Hot", "Active", "Warm"]
        definesPresentationContext = true

        self.tableView.tableHeaderView = controller.searchBar

        return controller
    })()

看到这个有点晚了,但以防其他人看到这个。从@Slavomir 代码中删除下面这两行应该会给你你正在寻找的结果,因为不需要设置 showsScopeBar。

self.resultSearchController.searchBar.showsScopeBar = true //移除 self.resultSearchController.searchBar.showsScopeBar = false //移除