【问题标题】:How to implement scopeButtonTitles for a customized UISearchBar?如何为自定义的 UISearchBar 实现 scopeButtonTitles?
【发布时间】:2017-01-24 14:24:15
【问题描述】:

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

【问题讨论】:

    标签: ios swift swift3 uisearchbar uisearchcontroller


    【解决方案1】:

    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
    }
    

    【讨论】:

    • 感谢您的回答,我尝试了您的方法,它有效。但它与 UISearchBar 重叠,而且它最初出现。实际上,我只想在用户点击搜索按钮后显示一个额外的按钮。另外,我正在硬编码 UISearchBar CGRect 的值。
    • @PradeshV 欢迎朋友 :)
    • 适用于 iOS 13+ searchController.automaticallyShowsScopeBar = true,这也解决了 Catalyst 问题。
    猜你喜欢
    • 2012-09-30
    • 2012-10-02
    • 2011-01-29
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    相关资源
    最近更新 更多