将 UISegmentedControl 与 UISearchController 一起使用

Posted

技术标签:

【中文标题】将 UISegmentedControl 与 UISearchController 一起使用【英文标题】:Using UISegmentedControl with UISearchController 【发布时间】:2015-12-15 13:21:44 【问题描述】:

如何将SegmentedControlUISearchController 一起使用?当SearchBar 处于非活动状态时,我需要SegmentedControlSearchBar 之下,并在SearchBar 被激活时隐藏分段控件。

我将 SearchController.searchBar 放在 tableview 标题中,所以我在故事板中定义的 SegmentedControlSearchBar 重叠。当我尝试通过调用 tableView.tableHeaderView?.addSubview(customSecmentedControl) 以编程方式在 viewDidLoad 中添加 SegmentedControl 时,它与 tableView 中的单元格重叠。

【问题讨论】:

【参考方案1】:

您不必连接自己的分段控件来处理此问题,因为 UISearchController 已经提供了该功能。

使用搜索栏的 scopeButtonTitles 属性设置范围栏的标题:

searchController.searchBar.scopeButtonTitles = ["Small", "Medium", "Large"]

您可以通过访问搜索栏的selectedScopeButtonIndex 属性来确定所选范围。

当范围改变时,搜索栏会发送它的委托通知:

func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int)

UISearchBar 和 UISearchBarDelegate 文档中提供了有关范围栏的更多详细信息。

【讨论】:

嗨!非常感谢您的回答。我尝试按照此处所述使用 scopeBar:raywenderlich.com/113772/uisearchcontroller-tutorial。但是,据我所知,scopeBar 仅在“SearchBar”处于活动状态时出现。我需要在搜索处于非活动状态时显示分段控件,并在用户在 tableView 中搜索某些内容时隐藏它。 您必须自己隐藏和显示它,但UISearchControllerDelegate 中的方法应该有助于实现这一点。 @FilippIgnatov 另一种方法是在导航栏中放置一个分段控件titleView。由于 searchBar 覆盖在导航栏上,所以它会在搜索时隐藏您的控件。【参考方案2】:

这对我有用。

    let searchController = UISearchController(searchResultsController: nil)

override func viewDidLoad() 
        super.viewDidLoad()

        searchController.searchBar.showsScopeBar = true

    

【讨论】:

以上是关于将 UISegmentedControl 与 UISearchController 一起使用的主要内容,如果未能解决你的问题,请参考以下文章

将 UISegmentedControl 与 UISearchController 一起使用

我可以将 pushViewController 与 UISegmentedControl 一起使用吗?

在不使用 alpha 的情况下使用 UISegmentedControl 在视图 ios 之间切换?

UISegmentedControl 不会取消选择旧段

如何使单个 UISegmentedControl 部分检测多个触摸

使用 UISegmentedControl 使用 uipickerview 在多个数组之间切换