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

标签 ios swift swift3 uisearchbar uisearchcontroller

我有一个自定义的 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 时。

最佳答案

设置showsScopeBar UISearchBar 的属性设置为 true 以显示 scopeBar。

customSearchController.customSearchBar.showsScopeBar = true

编辑:为此,您可以使用委托(delegate)方法 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
}

关于ios - 如何为自定义的 UISearchBar 实现 scopeButtonTitles?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41830610/

相关文章:

Swift:如何对笨拙但规则的 JSON 结构进行 DRY 可解码解析

swift - 如何将变量的值设置为在日期选择器中选择的小时值

ios - Xcode (Swift 3.0) - 在侧边栏菜单中切换 Controller 时如何保留值

ios - UITabBar Lifecycle 的方法不会从后台启动

ios - 如何将索引 check out 到工作目录中。它因错误 :Reference 'refs/heads/master' not found 而失败

arrays - 找到用户坐标和坐标数组之间最近的位置

swift - Anyobject 不是 NSLayoutConstraint 的子类型

ios - 仅对某些 View Controller 使用 Storyboard

ios - NSMutableDictionary 作为数据源 : can´t remove cell

iOS Swift - 如何获取本地和远程视频的宽高比?