UISearchController的简单应用

作者: Magenta_she | 来源:发表于2016-08-11 22:58 被阅读466次

    参考博客:

    UISearchController Tutorial: Getting Started

    使用UISearchController自定义搜索栏

    示意图:

    simulator

    #1 UISearchController简介

    iOS8以前,使用UISearchBar和UISearchDisplayController来实现搜索table view;iOS8以后才用的UISearchController。

    UISearchController不能再IB中显示,只能用编码进行初始化并配置。

    #2 默认搜索栏的实现

    1.加载并显示样本数据

    MasterViewController.swift

    接着,添加tableview的三个方法,单元数,行数,每行应该显示的内容。

    tableview的三个方法

    2.配置UISearchController

    --初始化UISearchController.传参是nil,表示展示结果的控制器和用于搜索的控制器在同一个视图控制器中。

    MasterViewController.swift

    --在ViewDidLoad方法里添加代码。

    MasterViewController.swift

    3.处理搜索结果

    --添加一个数组,存储搜索结果。

    MasterViewController.swift

    --添加一个方法来计算filteredCandies。遍历candies的每一个元素,把和searchText相同名字的candy存入filteredCandies。

    需要解释的两点:一是filter()里面套了一个闭包,闭包的参数是candy,返回值是Bool型的,关键字in引入闭包函数体。二是lowercaseString,这样的话,就不用考虑大小写问题了。

    MasterViewController.swift

    --更新searchResults。为了让MasterViewController能响应搜索栏,它必须遵守UISearchResultsUpdating协议,并实现这个方法。

    MasterViewController.swift

    --tableView上呈现搜索结果

    MasterViewController.swift

    现在来看一下效果

    simulator

    4.将数据传到DetailViewController

    MasterViewController.swift

    5.创建一个scopeBar来对结果分类过滤

    什么意思呢?让用户先选定一个category,再在指定的category里进行过滤。可供用户选择的有scopeBarButtonTitles有“All”“Chocolate”“Hard”“Others”。

    同上,这里的思路也是实现一个方法,然后再通过遵守一个协议,调用一个方法来实现。好,上代码。

    --在刚才filterContentForSearchText方法里,声明常量categoryMatch来检查scope的范围:要么是"All”,要么包含的是category的名字“Chocolate”,“Bar”,“Others“。返回值是categoryMatch以及搜索到的结果。

    MasterViewController.swift

    --调用这个方法。思路是:传参到filterContentForSearchText方法中,而这又和searchBar的两个属性相关,所以我们需要先调用searchBar相关的方法,而这又需要MasterViewController遵守UISearchBarDelegate这个协议。当用户选中scopeBar时,就调用delegate的这个方法。

    MasterViewController.swift

    --更新搜索结果

    同样,这里也是倒过来思考。需要传searchScope进去,那searchScope怎么求呢?哦,它是scopeButtonTitles数组里的一个元素,而这又需要调用searchBar。searchBar怎么求呢?它是searchController的一个属性。

    MasterViewController.swift

    --最后把scopeBar加到UI上

    ViewDidLoad()中

    最后,项目完成了!!!

    #3 自定义搜索栏

    对UI要求高的同学会问,搜索栏我想自定义怎么办?这个可以先去看参考博客,我写完CALayer的博客后会补充这部分的。

    相关文章

      网友评论

        本文标题:UISearchController的简单应用

        本文链接:https://www.haomeiwen.com/subject/gkpjsttx.html