如何为自定义的 UISearchBar 实现 scopeButtonTitles?

How to implement scopeButtonTitles for a customized UISearchBar?

我有一个自定义的 UISearchBar,当用户点击 searchBar 时,我想显示一个额外的按钮。因此,我使用 scopeButtonTitles 属性 来显示附加按钮。但是,它没有出现在 UISearchBar 上。

customSearchController = CustomSearchController(searchResultsController: self, searchBarFrame: CGRect(x: 0.0, y: 0.0, width: tableView.frame.size.width, height: 50.0), searchBarFont:  UIFont.systemFont(ofSize: 16.0),                                                             searchBarTextColor: UIColor.white, searchBarTintColor: UIColor.primaryBlue())
customSearchController.hidesNavigationBarDuringPresentation = false
customSearchController.dimsBackgroundDuringPresentation = false
customSearchController.customSearchBar.placeholder = NSLocalizedString("Search", comment: "Search")
customSearchController.customSearchBar.accessibilityLabel = customSearchController.searchBar.placeholder
//Scope Buttons
customSearchController.customSearchBar.scopeButtonTitles = [NSLocalizedString("List", comment: "List"), NSLocalizedString("Map", comment: "Map")]

如果我不使用自定义 UISearchBar,它工作正常。实际问题是当我要自定义 UISearchBar 时。

UISearchBarshowsScopeBar 属性 设置为 true 以显示 scopeBar。

customSearchController.customSearchBar.showsScopeBar = true

编辑: 为此,您可以使用委托方法 searchBarTextDidBeginEditing 并显示范围栏。

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    customSearchController.customSearchBar.showsScopeBar = true
    //set the frame so it will show scope bar properly.
}

现在,如果您想在搜索后隐藏 scoprBar,则可以使用 searchBarCancelButtonClicked 隐藏范围栏。

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    customSearchController.customSearchBar.showsScopeBar = false
    //set the frame again
}