Create a user interface with searchable content in a table view.
- 在表视图中创建具有可搜索内容的用户界面。
Overview
This sample demonstrates how to create a table view controller and search controller to manage the display of searchable content. It creates another custom table view controller to display the search results. This table view controller also acts as the presenter or provides context for the search results so they’re presented within their own context.
- 此示例演示如何创建
表视图控制器A
和搜索控制器B
以管理可搜索内容的显示。 它创建另一个自定义表视图控制器C
以显示搜索结果。 此表视图控制器C
还充当演示者或为搜索结果提供上下文,以便它们在自己的上下文中呈现。
This sample includes the optional—but recommended—UIStateRestoring
protocol. You adopt this protocol from the view controller class to save the search bar’s active state, first responder status, and search bar text and restore them when the app is relaunched.
- 此示例包含可选但建议的UIStateRestoring协议。 您从视图控制器类采用此协议来保存
1.搜索栏的活动状态
,2.第一响应者状态
和3.搜索栏文本
,并在重新启动应用程序时还原它们。
Create a Search Controller
Use MainTableViewController
, a subclass of UITableViewController
, to create a search controller. The search controller searches and filters a set of Product
objects and displays them in a table called ResultsTableController
. This table controller is displayed as the user enters a search string and is dismissed when the search is complete.
- 使用MainTableViewController(UITableViewController的子类)来创建搜索控制器。 搜索控制器搜索并过滤一组Product对象,并将它们显示在名为ResultsTableController的表中。 当用户输入搜索字符串时,将显示此表控制器,并在搜索完成时将其解除。
There are two ways to create the search controller in MainTableViewController
, depending on the iOS version. In iOS 10 and earlier, you place it inside the table view’s header. In iOS 11 and later, you place it in the view controller’s navigation bar.
- 根据iOS版本,有两种方法可以在
MainTableViewController
中创建搜索控制器。 在iOS 10及更早版本中,您将其放在表视图的标题中。 在iOS 11及更高版本中,您将其放在视图控制器的导航栏中。
Update the Search Results
This sample uses the UISearchResultsUpdating
protocol, along with NSComparisonPredicate
, to filter out search results from the group of available products. NSComparisonPredicate
is a foundation class that specifies how data should be fetched or filtered using search criteria. The search criteria are based on what the user types in the search bar, which can be a combination of product title, year introduced, and price.
- 此示例使用UISearchResultsUpdating协议以及NSComparisonPredicate来过滤掉可用产品组中的搜索结果。 NSComparisonPredicate是一个基础类,它指定如何使用搜索条件获取或过滤数据。 搜索条件基于用户在搜索栏中键入的内容,可以是产品标题,年份介绍和价格的组合。
To prepare for a search, the search bar content is trimmed of all leading and trailing space characters. Then the search string is passed to the findMatches
function, which returns the NSComparisonPredicate
used in the search. The product list results are applied to the search results table as a filtered list.
- 为了准备搜索,搜索栏内容将修剪所有前导和尾随空格字符。 然后将搜索字符串传递给
findMatches
函数,该函数返回搜索中使用的NSComparisonPredicate
。 产品列表结果将作为筛选列表应用于搜索结果表。