【iOS】Table View Programming Guide for iOS文档翻译

版权声明:本文为博主原创,如需转载请注明出处。

About Table Views in iOS Apps( iOS应用程序中的Table View)

Table views are versatile user interface objects frequently found in iOS apps. A table view presents data in a scrollable list of multiple rows that may be divided into sections.

Table view是在iOS应用程序中经常使用的多用途用户界面对象。 表格视图呈现多行可滚动列表中的数据,可将这些数据划分为多个section。

Table views have many purposes:

表格视图有很多目的:

  • To let users navigate through hierarchically structured data
  • To present an indexed list of items
  • To display detail information and controls in visually distinct groupings
  • To present a selectable list of options

  • 让用户浏览分层结构化的数据

  • 显示项目的索引列表
  • 以视觉上不同的分组显示详细信息和控件
  • 提供可选的选项列表

Figure I-1  Table views of various kinds

A table view has only one column and allows vertical scrolling only. It consists of rows in sections. Each section can have a header and a footer that displays text or an image. However, many table views have only one section with no visible header or footer. Programmatically, the UIKit framework identifies rows and sections through their index number: Sections are numbered 0 through n – 1 from the top of a table view to the bottom; rows are numbered 0 through n – 1 within a section. A table view can have its own header and footer, distinct from any section; the table header appears before the first row of the first section, and the table footer appears after the last row of the last section.

表格视图只有一列,只允许垂直滚动。 它由多个部分组成。 每个部分都可以有一个标题和一个显示文字或图像的页脚。 但是,许多表视图只有一个部分没有可见的页眉或页脚。 以编程方式,UIKit框架通过它们的索引号来标识行和部分:部分从表视图的顶部到底部编号为0到n - 1; 行在一个段内从0到n - 1编号。表格视图可以有自己的页眉和页脚,与任何章节截然不同; 表格标题出现在第一部分的第一行之前,并且表格页脚出现在最后一部分的最后一行之后。

At a Glance (概览)

A table view is an instance of the UITableView class in one of two basic styles, plain or grouped. A plain table view is an unbroken list; a grouped table view has visually distinct sections. A table view has a data source and might have a delegate. The data source object provides the data for populating the sections and rows of the table view. The delegate object customizes its appearance and behavior.

表视图是UITableView类的一个实例,它是两种基本样式之一,plain或grouped。 普通表格视图是一个不间断的列表; 分组表格视图具有视觉上不同的部分。 表格视图有一个数据源并可能有一个代理 。 数据源对象提供用于填充表视图的部分和行的数据。 代理对象定制其外观和行为。

Table Views Draw Their Rows Using Cells (表视图使用单元格绘制其行)

A table view draws its visible rows using cells—that is, UITableViewCell objects. Cells are views that can display text, images, or other kinds of content. They can have background views for both normal and selected states. Cells can also have accessory views, which function as controls for selecting or setting an option.

表视图使用单元格绘制其可见行 - 即UITableViewCell对象。 单元格是可以显示文本,图像或其他类型内容的视图。 他们可以拥有正常和选定状态的背景视图。 cell 还可以有附件视图,用作选择或设置选项的控件。

The UIKit framework defines four standard cell styles, each with its own layout of the three default content elements: main label, detail label, and image. You may also create your own custom cells to acquire a distinctive style for your app’s table views.

UIKit框架定义了四种标准单元格样式,每种样式都具有三种默认内容元素(主标签,详细标签和图像)的布局。 您也可以创建自己的自定义单元格,以获取应用程序的表格视图的独特风格。

When you configure the attributes of a table view in the storyboard editor, you choose between two types of cell content: static cells or dynamic prototypes.

在故事板编辑器中配置表格视图的属性时,可以在两种类型的单元格内容中进行选择:静态单元格或动态原型。

  • Static cells. Use static cells to design a table with a fixed number of rows, each with its own layout. Use static cells when you know what the table looks like at design time, regardless of the specific information it displays.
  • Dynamic prototypes. Use dynamic prototypes to design one cell and then use it as the template for other cells in the table. Use a dynamic prototype when multiple cells in a table should use the same layout to display information. Dynamic prototype content is managed by the data source at runtime, with an arbitrary number of cells.

  • 静态单元格 。 使用静态单元设计具有固定行数的表格,每个表格都有自己的布局。 不管显示的具体信息如何,在设计时知道表的外观时,请使用静态单元格。

  • 动态原型 。 使用动态原型设计一个单元格,然后将其用作表格中其他单元格的模板。 当表中的多个单元格应使用相同的布局来显示信息时,请使用动态原型。 动态原型内容由运行时的数据源进行管理,具有任意数量的单元。

Responding to Selections of Rows (响应选中的行)

When users select a row (by tapping it), the delegate of the table view is informed via a message. The delegate is passed the indexes of the row and the section that the row is in. It uses this information to locate the corresponding item in the app’s data model. This item might be at an intermediate level in the hierarchy of data or it might be a “leaf node” in the hierarchy. If the item is at an intermediate level, the app displays a new table view. If the item is a leaf node, the app displays details about the selected item in a grouped-style table view or some other kind of view.

当用户选择一行(通过点击它)时,表视图的代理通过消息被通知。 该代理会传递该行的索引和该行所在的部分。它使用此信息在应用程序的数据模型中找到相应的项目。 此项可能处于数据层次结构的中间级别,或者它可能是层次结构中的“叶节点”。如果项目处于中间级别,则应用程序将显示新的表格视图。如果项目是叶节点,该应用程序在分组样式的表格视图或某种其他类型的视图中显示有关所选项目的详细信息。

In table views that list a series of options, tapping a row simply selects its associated option. No subsequent view of data is displayed.

在列出一系列选项的表格视图中,点击一行即可选择相关的选项。 没有显示后续的数据视图。

In Editing Mode You Can Add, Delete, and Reorder Rows (在编辑模式下,您可以添加,删除和重新排列行)

Table views can enter an editing mode in which users can insert or delete rows, or relocate them within the table. In editing mode, rows that are marked for insertion or deletion display a green plus sign (insertion) or a red minus sign (deletion) near the left edge of the row. If users touch a deletion control or, in some table views, swipe across a row, a red Delete button appears, prompting users to delete that row. Rows that can be relocated display (near their right edge) an image consisting of several horizontal lines. When the table view leaves editing mode, the insertion, deletion, and reordering controls disappear.

表视图可以进入编辑模式,用户可以在该模式下插入或删除行,或者在表内重新定位行。 在编辑模式下,标记为插入或删除的行在行左边附近显示绿色加号(插入)或红色减号(删除)。 如果用户触摸删除控件,或者在某些表格视图中横跨一行进行滑动,则会出现一个红色的“删除”按钮,提示用户删除该行。 可以重新定位的行(靠近其右边缘)显示由多条水平线组成的图像。 当表格视图离开编辑模式时,插入,删除和重新排序控制消失。

When users attempt to insert, delete, or reorder rows, the table view sends a sequence of messages to its data source and delegate so that they can manage these operations.

当用户尝试插入,删除或重新排序行时,表视图将一系列消息发送到其数据源和代理,以便他们可以管理这些操作。

To Create a Table View, Use a Storyboard(要创建表视图,请使用Storyboard)

The easiest and recommended way to create and manage a table view is to use a custom UITableViewController object in a storyboard. If your app is based largely on table views, create your Xcode project using the Master-Detail Application template. This template includes an initial custom UITableViewController class and a storyboard for the scenes in the user interface, including the custom view controller and its table view. In the storyboard editor, choose one of the two styles for this table view and design its content.

创建和管理表格视图的最简单和推荐的方法是在故事板中使用自定义的UITableViewController对象。 如果您的应用程序主要基于表视图,请使用Master-Detail Application template创建您的Xcode项目。 该模板包含一个初始的自定义UITableViewController类和一个用户界面场景的故事板,包括自定义视图控制器及其表格视图。 在故事板编辑器中,为此表格视图选择两种样式中的一种并设计其内容。

At runtime, UITableViewController creates the table view and assigns itself as delegate and data source. Immediately after it’s created, the table view asks its data source for the number of sections, the number of rows in each section, and the table view cell to use to draw each row. The data source manages the application data used for populating the sections and rows of the table view.

在运行时, UITableViewController创建表视图并将自己指定为代理和数据源。 在创建后,表视图会向其数据源询问段的数量,每段中的行数以及用于绘制每行的表视图单元格。 数据源管理用于填充表视图的部分和行的应用程序数据。

Prerequisites(先决条件)

Before reading this document, you should read Start Developing iOS Apps Today to understand the basic process for developing iOS apps. Then read View Controller Programming Guide for iOS for a comprehensive look at view controllers and storyboards. Finally, to gain valuable hands-on experience using table views in a storyboard, read the tutorial Your Second iOS App: Storyboards.

在阅读本文档之前,您应该阅读 立即开始开发iOS应用程序 了解开发iOS应用程序的基本过程。 然后阅读适用于iOS的View Controller编程指南,以全面了解视图控制器和故事板。最后,为了在故事板中使用表格视图获得宝贵的实践经验,请阅读教程 你的第二个iOS应用程序:故事板 。

The information presented in this introduction and in Table View Styles and Accessory Views summarizes prescriptive information on table views presented in iOS Human Interface Guidelines. You can find a complete description of the styles and characteristics of table views, as well as their recommended uses, in the chapter Content Views.

本介绍和表格视图样式和附件视图中显示的信息总结了表格视图的规定信息 iOS人机界面指南 。 您可以在本章中找到关于表格视图样式和特征的完整说明,以及它们的推荐用途 内容视图 。

See Also(也可以看看)

You will find the following sample code projects to be instructive models for your own table view implementations:

  • SimpleDrillDown project
  • Table View Animations and Gestures project
    For guidance on how to use the standard container view controllers provided by UIKit, see View Controller Catalog for iOS. This document describes split view controllers and navigation controllers, which can both contain table view controllers as children.

您会发现以下示例代码项目是您自己的表视图实现的指导性模型:

  • SimpleDrillDown 项目
  • 表视图动画和手势项目
    有关如何使用UIKit提供的标准容器视图控制器的指导,请参阅适用于iOS的View Controller Catalog 。 本文档介绍了分割视图控制器和导航控制器,它们都可以包含表视图控制器作为子项。

Table View Styles and Accessory Views(表视图样式和附件视图)

Table views come in distinctive styles that are suitable for specific purposes. In addition, the UIKit framework provides standard styles for the cells used to draw the rows of table views. It also gives you standard accessory views (that is, controls) that you can include in cells.

表视图以独特的风格呈现,适合特定用途。 另外,UIKit框架为用于绘制表格视图行的单元格提供标准样式。 它还为您提供标准配件视图(即控件),您可以将其包含在单元格中。

Table View Styles(表视图样式)

There are two major styles of table views: plain and grouped. The two styles are distinguished mainly by appearance.

有两种主要的表格视图样式:plain和grouped。 这两种风格主要通过外观来区分。

Plain Table Views(普通表格视图)

A table view in the plain (or regular) style displays rows that stretch across the screen and have a creamy white background (see Figure 1-1). A plain table view can have one or more sections, sections can have one or more rows, and each section can have its own header or footer title. (A header or footer may also have a custom view, for instance one containing an image). When the user scrolls through a section with many rows, the header of the section floats to the top of the table view and the footer of the section floats to the bottom.

以plain(或常规)样式显示的表格视图可显示横跨屏幕并具有奶白色背景的行(请参阅图1-1 )。 plain表格视图可以有一个或多个section,section可以有一个或多个行,每个section可以有自己的页眉或页脚标题。 (页眉或页脚也可以具有自定义视图,例如包含图像的视图)。 当用户滚动浏览多行的部分时,部分的标题浮动到表视图的顶部,部分的页脚浮动到底部。

Figure 1-1  A table view in the plain style

A variation of plain table views associates an index with sections for quick navigation; Figure 1-2 shows an example of this kind of table view, which is called an indexed list. The index runs down the right edge of the table view. Entries in the index correspond to section header titles. Touching an item in the index scrolls the table view to the associated section. For example, the section headings could be two-letter state abbreviations, and the rows for a section could be the cities in that state; touching at a certain spot in the index displays the cities for the selected state. The rows in indexed lists should not have disclosure indicators or detail disclosure buttons, because these interfere with the index.

plain表格视图的变体将索引与快速导航的部分相关联; 图1-2显示了这种表视图的一个例子,它被称为索引列表 。 索引沿着表格视图的右边缘向下延伸。 索引中的条目对应于节标题标题。 触摸索引中的项目可将表格视图滚动到关联的部分。 例如,section标题可以是双字母状态缩写,而section的行可以是该州的城市; 触摸索引中的某个点显示所选状态的城市。 索引列表中的行不应该有披露指标或详细披露按钮,因为这些行会干扰索引。

Figure 1-2  A table view configured as an indexed list

The simplest kind of table view is a selection list (see Figure 1-3). A selection list is a plain table view that presents a menu of options that users can select. It can limit the selection to one row or allow multiple selections. A selection list marks a selected row with a checkmark (see Figure 1-3).

最简单的表格视图是一个选择列表( 见图1-3 )。 选择列表是一个普通表格视图,显示用户可以选择的选项菜单。 它可以将选择限制为一行或允许多个选择。 选择列表用选中标记选中一行(参见图1-3 )。

Figure 1-3  A table view configured as a selection list

Grouped Table Views

A grouped table view also displays a list of information, but it groups related rows in visually distinct sections. As shown in Figure 1-4, each section has rounded corners and by default appears against a bluish-gray background. Each section may have text or an image for its header or footer to provide some context or summary for the section. A grouped table works especially well for displaying the most detailed information in a data hierarchy. It allows you to separate details into conceptual groups and provide contextual information to help users understand it quickly.

grouped表格视图还显示信息列表,但它在视觉上不同的部分将相关的行分组。 如图1-4所示,每个部分都有圆角,默认情况下会出现蓝灰色的背景。 每个部分可以具有文本或图像作为其页眉或页脚,以为该部分提供一些上下文或摘要。 分组表特别适用于在数据层次结构中显示最详细的信息。 它允许您将细节分解为概念组,并提供上下文信息以帮助用户快速理解。

Figure 1-4  A table view in the grouped style

The headers and footers of sections in a grouped table view have relative locations and sizes as indicated in Figure 1-5.

分组表格视图中部分的页眉和页脚具有相对位置和大小, 如图1-5所示 。

Figure 1-5  Header and footer of a section

On iPad devices, a grouped table view automatically gets wider margins when the table view itself is wide.

在iPad设备上,当表格视图本身很宽时,分组表格视图会自动获得更宽的边距。

Standard Styles for Table View Cells(表格视图单元格的标准样式)

In addition to defining two styles of table views, the UIKit framework defines four styles for the cells that a table view uses to draw its rows. You may create custom table view cells with different appearances if you want, but these four predefined cell styles are suitable for most purposes. The techniques for creating table view cells in a predefined style and for creating custom cells are described in A Closer Look at Table View Cells.

除了定义两种表格视图风格之外,UIKit框架还为表格视图用于绘制行的单元格定义了四种样式。 如果需要,您可以创建具有不同外观的自定义表格视图单元格,但这四种预定义单元格样式适用于大多数目的。 在“查看表格视图单元格”中描述了以预定义样式创建表格视图单元格和创建自定义单元格的技术 。

The default style for table view rows uses a simple cell style that has a single title and an optional image (Figure 1-6). This style is associated with the UITableViewCellStyleDefault constant.

表格视图行的默认样式使用简单的单元格样式,该样式具有单个标题和可选图像( 图1-6 )。 此样式与UITableViewCellStyleDefault常量关联。

Figure 1-6  Default table row style

The cell style for the rows in Figure 1-7 left-aligns the main title and puts a gray subtitle under it. It also permits an image in the default image location. This style is associated with the UITableViewCellStyleSubtitle constant.

图1-7中行的单元格样式左对齐主标题,并在其下放置灰色字幕。 它还允许默认图像位置中的图像。 这种风格与UITableViewCellStyleSubtitle常量相关联。

Figure 1-7  Table row style with a subtitle under the title

The cell style for the rows in Figure 1-8 left-aligns the main title. It puts the subtitle in blue text and right-aligns it on the right side of the row. Images are not permitted. This style is used in the Settings app, where the subtitle indicates the current setting for a preference. It is associated with the UITableViewCellStyleValue1 constant.

图1-8中的行的单元格样式左对齐主标题。 它将字幕放在蓝色文本中,并将其右对齐到该行的右侧。 图像不被允许。 此样式用于“设置”应用中,其中字幕指示首选项的当前设置。 它与UITableViewCellStyleValue1常量相关联。

Figure 1-8  Table row style with a right-aligned subtitle

The cell style for the rows in Figure 1-9 puts the main title in blue and right-aligns it at a point that’s indented from the left side of the row. The subtitle is left aligned at a short distance to the right of this point. This style does not allow images. It is used in the Contacts part of the Phone app and is associated with the UITableViewCellStyleValue2 constant.

图1-9中的行的单元格样式将主标题设置为蓝色,并将其右对齐,该行从左侧开始缩进。 小标题左对齐在这一点的右边一小段距离。 这种风格不允许图像。 它在Phone应用程序的Contacts部分中使用,并与UITableViewCellStyleValue2常量关联。

Figure 1-9  Table row style in Contacts format

Accessory Views(配件视图)

There are three standard kinds of accessory views (shown with their accessory-type constants):

有三种标准配件视图(用附件类型常量显示):

Disclosure indicator—UITableViewCellAccessoryDisclosureIndicator. You use the disclosure indicator when selecting a cell results in the display of another table view reflecting the next level in the data model hierarchy.

发现指示器 - UITableViewCellAccessoryDisclosureIndicator 。 在选择单元格时,使用发现指示器会显示反映数据模型层次结构中下一个级别的其他表视图。

Detail disclosure button—UITableViewCellAccessoryDetailDisclosureButton. You use the detail disclosure button when selecting a cell results in a detail view of that item (which may or may not be a table view).

详细信息显示按钮 - UITableViewCellAccessoryDetailDisclosureButton 。 在选择单元格时,您可以使用详细信息显示按钮导出该项目的详细视图(可能是或不是表格视图)。

Checkmark—UITableViewCellAccessoryCheckmark. You use a checkmark when a touch on a row results in the selection of that item. This kind of table view is known as a selection list, and it is analogous to a pop-up list. Selection lists can limit selections to one row, or they can allow multiple rows with checkmarks.

选中标记 - UITableViewCellAccessoryCheckmark 。 当触摸某一行会导致选择该项目时,您会使用复选标记。 这种表格视图被称为选择列表,类似于弹出列表。 选择列表可以将选择限制为一行,或者可以允许具有复选标记的多行。

Instead of the standard accessory views, you may specify a control (for example, a switch) or a custom view as the accessory view.

作为附件视图,您可以指定控件(例如开关)或自定义视图,而不是标准附件视图。

Overview of the Table View API(Table View API概述)

The table view programming interface includes several UIKit classes, two formal protocols, and a category added to a Foundation framework class.

表视图编程接口包括几个UIKit类,两个正式的 协议 ,和一个类别 添加到基础框架类。

Table View

A table view itself is an instance of the UITableView class. You use its methods to configure the appearance of the table view—for example, specifying the default height of rows or providing a subview used as the header for the table. Other methods give you access to the currently selected row as well as specific rows or cells. You can call other methods of UITableView to manage selections, scroll the table view, and insert or delete rows and sections.

表视图本身是UITableView类的一个实例。 您可以使用它的方法来配置表视图的外观,例如,指定行的缺省高度或提供用作表的标题的子视图。 其他方法可让您访问当前选定的行以及特定的行或单元格。 您可以调用UITableView其他方法来管理选择,滚动表视图以及插入或删除行和部分。

UITableView inherits from the UIScrollView class, which defines scrolling behavior for views with content larger than the size of the window. UITableView redefines the scrolling behavior to allow vertical scrolling only.

UITableView继承自UIScrollView类,该类定义了内容大于窗口大小的视图的滚动行为。 UITableView重新定义了滚动行为,只允许垂直滚动。

Table View Controller

The UITableViewController class manages a table view and adds support for many standard table-related behaviors such as selection management, row editing, table configuration, and others. This additional support is there to minimize the amount of code you have to write to create and initialize your table-based interface. You don’t use this class directly—instead you subclass UITableViewController to add custom behaviors.

UITableViewController类管理一个表视图,并添加对许多标准表相关行为的支持,如选择管理,行编辑,表格配置等。 这种额外的支持是为了最大限度地减少创建和初始化基于表格的界面所需编写的代码量。 你不直接使用这个类 - 而是你的子类UITableViewController添加自定义行为。

Data Source and Delegate

A UITableView object must have a delegate and a data source. Following the Model-View-Controller design pattern, the data source mediates between the app’s data model (that is, its model objects) and the table view. The delegate, on the other hand, manages the appearance and behavior of the table view. The data source and the delegate are often (but not necessarily) the same object, and that object is usually a custom subclass of UITableViewController. (See Navigating a Data Hierarchy with Table Views for further information.)

一个UITableView对象必须有一个 代表和数据源 。 之后 模型-视图-控制器 设计模式中,数据源在应用程序的数据模型(即其数据模型)之间作为 模型对象 和表格视图的中介。另一方面,代理管理表视图的外观和行为。 数据源和代理通常(但不一定)是同一个对象,并且该对象通常是UITableViewController的自定义子类。 (请参阅使用表视图导航数据层次结构以获取更多信息。)

The data source adopts the UITableViewDataSource protocol. UITableViewDataSource has two required methods. The tableView:numberOfRowsInSection: method tells the table view how many rows to display in each section, and the tableView:cellForRowAtIndexPath: method provides the cell to display for each row in the table. Optional methods allow the data source to configure multiple sections, provide headers and/or footers, and support adding, removing, and reordering rows in the table.

数据源采用UITableViewDataSource协议。 UITableViewDataSource有两个必需的方法。 tableView:numberOfRowsInSection:方法告诉表视图在每个部分中显示多少行, tableView:cellForRowAtIndexPath:方法提供要显示表中每一行的单元格。 可选方法允许数据源配置多个section,提供页眉和/或页脚,并支持添加,删除和重新排序表中的行。

The delegate adopts the UITableViewDelegate protocol. This protocol has no required methods. It declares methods that allow the delegate to modify visible aspects of the table view, manage selections, support an accessory view, and support editing of individual rows in a table.

该代理采用UITableViewDelegate协议。 该协议没有必要的方法。 它声明允许委托修改表视图的可见方面,管理选择,支持附件视图以及支持编辑表中单个行的方法。

An app can make use of the convenience class UILocalizedIndexedCollation to help the data source organize the data for indexed lists and display the proper section when users tap an item in the index. The UILocalizedIndexedCollation class also localizes section titles.

应用程序可以使用便利的UILocalizedIndexedCollation类来帮助数据源组织索引列表的数据,并在用户点击索引中的项目时显示正确的部分。UILocalizedIndexedCollation类还可以定位节标题。

Extension to the NSIndexPath Class(对NSIndexPath类的扩展)

Many table view methods use index paths as parameters or return values. An index path identifies a path to a specific node in a tree of nested arrays, and in the Foundation framework it is represented by an NSIndexPath object. UIKit declares a category on NSIndexPath with methods that return key paths, locate rows in sections, and construct NSIndexPath objects from row and section indexes. For more information, see NSIndexPath UIKit Additions.

许多表视图方法使用索引路径作为参数或返回值。 索引路径标识嵌套数组树中特定节点的路径,而在Foundation框架中,它由NSIndexPath对象表示。 UIKit声明了一个 类别 在NSIndexPath使用返回键路径的方法,在部分中定位行,并根据行和部分索引构造NSIndexPath对象。 有关更多信息,请参阅 NSIndexPath UIKit添加 。

Table View Cells

As noted in Data Source and Delegate, the data source must return a cell object for each visible row that a table view displays. These cell objects must inherit from the UITableViewCell class. This class includes methods for managing cell selection and editing, managing accessory views, and configuring the cell. You can instantiate cells directly in the standard styles defined by the UITableViewCell class and give these cells content consisting of one or two strings of text and, in some styles, both image and text. Instead of using a cell in a standard style, you can put your own custom subviews in the content view of an “off-the-shelf” cell object. You may also subclass UITableViewCell to customize the appearance and behavior of table view cells. These approaches are all discussed in A Closer Look at Table View Cells.

如数据源和代理中所述,数据源必须为表视图显示的每个可见行返回一个单元对象。 这些单元对象必须从UITableViewCell类继承。 该课程包括管理单元格选择和编辑,管理配件视图以及配置单元格的方法。 您可以 实例 单元格直接处于由UITableViewCell类定义的标准样式中,并为这些单元格提供由一个或两个文本字符串组成的内容,并且在某些样式中包含图像和文本。 您可以将自己的自定义子视图放置在“现成”单元对象的内容视图中,而不是使用标准样式的单元。 您也可以继承UITableViewCell以定制表格视图单元格的外观和行为。 这些方法都在“仔细查看表格视图单元格”中讨论 。

Navigating a Data Hierarchy with Table Views(使用表视图浏览数据层次结构)

A common use of table views—and one to which they’re ideally suited—is to navigate hierarchies of data. A table view at a top level of the hierarchy lists categories of data at the most general level. Users select a row to “drill down” to the next level in the hierarchy. At the bottom of the hierarchy is a view (often a table view) that presents details about a specific item (for example, an address book record) and may allow users to edit the item. This section explains how you can map the levels of the data model hierarchy to a succession of table views and describes how you can use the facilities of the UIKit framework to help you implement such navigation-based apps.

表视图的一种常见用法 - 以及它们最适合的一种 - 是浏览数据层次结构。 层级顶层的表格视图以最一般的级别列出数据类别。 用户选择一行以“向下钻取”到层次结构中的下一个级别。 层次结构的底部是一个视图(通常是一个表视图),用于呈现特定项目的详细信息(例如,地址簿记录),并允许用户编辑该项目。 本节介绍如何将数据模型层次结构的级别映射到一系列表视图,并介绍如何使用UIKit框架的功能来帮助您实现这种基于导航的应用程序。

Hierarchical Data Models and Table Views(分层数据模型和表视图)

For a navigation-based app, you typically design your app data as a graph of model objects that is sometimes referred to as the app’s data model. You can then implement the model layer of your app using various mechanisms or technologies, including Core Data, property lists, or archives of custom objects. Regardless of the approach, the traversal of your app’s data model follows patterns that are common to all navigation-based apps. The data model has hierarchical depth, and objects at various levels of this hierarchy should be the source for populating the rows of a table view.

对于基于导航的应用程序,您通常将您的应用程序数据设计为图表 模型对象 这有时被称为应用程序的数据模型 。 然后,您可以使用各种机制或技术来实现应用程序的模型层,这些机制或技术包括Core Data, property lists , archives 或者自定义对象。 无论如何,遍历应用程序的数据模型都遵循所有基于导航的应用程序通用的模式。 数据模型具有分层深度,并且此层次结构的各个级别的对象应该是填充表视图的行的源。

Note: To learn about the Core Data technology and framework, see Core Data Starting Point.
注意:要了解核心数据技术和框架,请参阅 核心数据起点 。

The Data Model as a Hierarchy of Model Objects (数据模型作为模型对象的层次结构)

A well-designed app factors its classes and objects in a way that conforms to the Model-View-Controller (MVC) design pattern. The app’s data model consists of the model objects in this pattern. You can describe model objects (using the terminology provided by the object modeling pattern) in terms of their properties. These properties are of two general kinds: attributes and relationships.

一个设计良好的应用程序将其类和对象按照符合的方式进行分解 模型-视图-控制器 (MVC)设计模式。 应用程序的数据模型由此模式中的模型对象组成。 您可以描述模型对象(使用由 对象建模 模式提供的术语))就其属性而言。 这些属性有两种一般类型:属性和关系。

Note: The notion of “property” here is abstractly related to, but not identical with, the declared property feature of Objective-C. A class definition typically represents properties programmatically through instance variables and declared properties.

注意:这里的“property”的概念是比较抽象的相关,但与Objective-C的特性声明属性不相同 。 一个 类定义 通常通过实例变量和声明属性以编程方式表示属性。

Attributes represent elements of model-object data. Attributes can range from an instance of a primitive class (for example, an NSString, NSDate, or UIColor object) to a C structure or a simple scalar value. Attributes are generally what you use to populate a table view that represents a “leaf node” of the data hierarchy and that presents a detail view of that item.

属性表示模型对象数据的元素。 属性的范围可以从 原始类的实例 (例如, NSString , NSDate或UIColor对象)转换为C结构或简单标量值。 属性通常用于填充表示数据层次结构的“叶节点”的表视图,并提供该项目的详细视图。

A model object may also have relationships with other model objects. It is through these relationships that a data model acquires hierarchical depth by composing an object graph. Relationships are of two general kinds in terms of cardinality: to-one and to-many. To-one relationships define an object’s relationship with another object (for example, a parent relationship). A to-many relationship, on the other hand, defines an object’s relationship with multiple objects of the same kind. The to-many relationship is characterized by containment and can be programmatically represented by collections such as NSArray objects (or, simply, arrays). An array might contain other arrays, or it could contain multiple dictionaries, which are collections that identify their contained values through keys. Dictionaries, in turn, can contain one or more other collections, including arrays, sets, and even other dictionaries. As collections nest in other collections, your data model can acquire hierarchical depth.

模型对象也可能与其他模型对象有关系。 通过这些关系,数据模型通过组成对象图获取层级深度。 在基数方面,关系有两种一般类型:一对一和多对多。 一对一关系定义一个对象与另一个对象的关系(例如,父亲关系)。 另一方面,一对多关系定义了一个对象与多个同类对象的关系。 多对多关系的特点是遏制,并可以用编程方式表示 集合 如NSArray对象(或简单地说,数组)。 一个数组可能包含其他数组,或者可能包含多个字典,这些字典是通过键标识其包含的值的集合。 字典反过来可以包含一个或多个其他集合,包括数组,集合甚至其他字典。 由于集合嵌套在其他集合中,因此您的数据模型可以获取分层深度。

Table Views and the Data Model(表视图和数据模型)

The rows of a plain table view are typically backed by collection objects of the app’s data model; these objects are usually arrays. Arrays contain strings or other elements that a table view can use when displaying row content. When you create a table view (described in Creating and Configuring a Table View), it immediately queries its data source for its dimensions—that is, it requests the number of sections and the number of rows per section—and then asks for the content of each row. The data source fetches this content from an array in the appropriate level of the data-model hierarchy.

普通表视图的行通常由后台支持 ,收集对象 的应用程序数据模型; 这些对象通常是数组。 数组包含字符串或表视图在显示行内容时可以使用的其他元素。 当你创建一个表格视图(在创建和配置表格视图中描述)时,它立即查询它的表格 数据源 因为它的尺寸 - 也就是说,它要求section的个数,以及section中的行数 - 然后要求每行的内容。 数据源从数据模型层次结构的适当级别的数组中获取此内容。

In many of the methods defined for a table view’s data source and delegate, the table view passes in an index path to identify the section and row that is the focus of the current operation—for example, fetching content for a row or indicating the row the user tapped. An index path is an instance of the Foundation framework’s NSIndexPath class that you can use to identify an item in a tree of nested arrays. The UIKit framework extends NSIndexPath to add a section and a row property to the class. The data source should use these properties to map a section and row of the table view to a value at the corresponding index of the array being used as the table view’s source of data.

在许多为表格视图的数据源和代理定义的方法中 ,表视图在索引路径中传递以标识作为当前操作焦点的section和row,例如,获取行的内容或指示用户点击的行。 索引路径是Foundation框架的NSIndexPath类的一个实例,可用于标识嵌套数组树中的项目。 UIKit框架扩展NSIndexPath以添加一个section和row 属性 给一个类。 数据源应该使用这些属性将表视图的section和row映射到用作表视图的数据源的数组的相应索引处的值。

In the sequence of table views in Figure 3-1, the top level of the data hierarchy is an array of four arrays, with each inner array containing objects representing the trails for a particular region. When the user selects one of these regions, the next table view lists names identifying the trails within the selected array. When the user selects a particular trail, the next table view describes that trail using a grouped table view.

在图3-1中的表格视图序列中,数据层次结构的顶层是一个由四个数组组成的数组,每个数组的内部数组包含表示特定区域的轨迹的对象。 当用户选择这些区域中的一个时,下一个表格视图将列出标识所选阵列中的路径的名称。 当用户选择特定的路径时,下一个表格视图使用分组表格视图来描述该路径。

Figure 3-1  Mapping levels of the data model to table views

Note: You could easily redesign the app in Figure 3-1 to have only two table views. The first table view would be an indexed list of trails by region. The second table view would display the detail for a selected trail.
注意:您可以轻松地重新设计图3-1中的应用程序,使其只有两个表格视图。 第一个表格视图将是按地区列出的索引列表。 第二个表格视图将显示选定线索的详细信息。

View Controllers and Navigation-Based Apps

The UIKit framework provides a number of view controller classes for managing common user interface patterns in iOS. View controllers are controller objects that inherit from the UIViewController class. They are an essential tool for view management, especially when an app uses those views to present successive levels of its data hierarchy. This section describes how two subclasses of UIViewController, navigation controllers and table view controllers, present and manage a succession of table views.

UIKit框架提供了许多视图控制器类来管理iOS中的通用用户界面模式。 视图控制器是 控制器对象 从UIViewController类继承。 它们是视图管理的重要工具,尤其是当应用程序使用这些视图呈现其数据层次结构的连续级别时。 本节介绍UIViewController ,导航控制器和表视图控制器的两个子类如何呈现和管理一系列表视图。

Note: This section gives an overview of view controllers to provide some background for the coding tasks discussed later in this document. To learn about view controllers in depth, see View Controller Programming Guide for iOS.

注意:本节概述视图控制器,为本文稍后讨论的编码任务提供一些背景知识。 要深入了解视图控制器,请参阅适用于iOS的视图控制器编程指南 。

The UINavigationController class inherits from UIViewController, a base class that defines the common programmatic interface and behavior for controller objects that manage views in iOS. Through inheritance from this base class, a view controller acquires an interface for general view management. After it implements parts of this interface, a view controller can autorotate its view, respond to low-memory notifications, overlay “modal” views, respond to taps on the Edit button, and otherwise manage the view.

UINavigationController类继承自UIViewController , UIViewController是一个基类,它定义了公共编程接口和行为,为 控制器对象 在iOS中管理视图。 通过继承此基类,视图控制器获取一般视图管理的接口。 在它实现了该接口的一部分后,视图控制器可以自动控制其视图,响应低内存通知,覆盖“模态”视图,响应“编辑”按钮上的轻击,并以其他方式管理视图。

A navigation controller maintains a stack of view controllers, one for each of the table views displayed (see Figure 3-2). It begins with what’s known as the root view controller. When the user taps a row of the table view (often on a detail disclosure button), the root view controller pushes the next view controller onto the stack. The new view controller’s table view visually slides into place from the right, and the navigation bar items are updated appropriately. When users tap the back button in the navigation bar, the current view controller is popped off the stack. As a consequence, the navigation controller displays the table view managed by the view controller that is now at the top of the stack.

导航控制器维护视图控制器的一个栈,每个显示的表视图都有一个控制器( 见图3-2 )。 它以所谓的根视图控制器开始 。 当用户点击表格视图的一行时(通常在详细发现按钮上),根视图控制器将下一个视图控制器推入栈。 新的视图控制器的表格视图从右侧以可视方式滑入,并且导航栏项目被适当更新。 当用户点击导航栏中的后退按钮时,当前视图控制器将弹出堆栈。 因此,导航控制器将显示现在位于栈顶部的视图控制器管理的表视图。

Figure 3-2  Navigation controller and view controllers in a navigation-based app

Navigation bars are a user-interface device that enables users to navigate a hierarchy of data. Users start with general, top-level items and “drill down” the hierarchy to detailed views showing specific properties of leaf-node items. The view below the navigation bar presents the current level of data. A navigation bar includes a title for the current view and, if that view is lower in the hierarchy than the top level, a back button on the left side of the bar; the back button is a navigation control that the user taps to return to the previous level. (The back button by default displays the title for the previous view.) A navigation bar may also have an Edit button—used to enter editing mode for the current view—or custom buttons for functions that manage content (see Figure 3-3).

导航栏是一个用户界面设备,使用户能够导航数据层次结构。 用户从一般的顶级项目开始,并将层次结构“向下钻取”到详细的视图,其中显示了叶节点项目的特定属性。 导航栏下方的视图显示当前的数据级别。 导航栏包含当前视图的标题,如果该视图在层次结构中低于顶层,则在该栏左侧有一个后退按钮; 后退按钮是用户点击返回到前一级的导航控件。 (后退按钮默认显示前一个视图的标题。)导航栏还可能有一个编辑按钮 - 用于进入当前视图的编辑模式 - 或管理内容的功能的自定义按钮(请参见图3-3 ) 。

Figure 3-3  Navigation bars and common control items

A UINavigationController manages the navigation bar, including the items that are displayed in the bar for the view below it. A UIViewController object manages a view displayed below the navigation bar. For this view controller, you create a subclass of UIViewController or a subclass of a view controller class that the UIKit framework provides for managing a particular type of view. For table views, this view controller class is UITableViewController. For a navigation controller that displays a sequence of table views reflecting levels within a data hierarchy, you need to create a separate custom table view controller for each table view.

一个UINavigationController管理导航栏,包括在它下面的视图栏中显示的项目。 UIViewController对象管理导航栏下显示的视图。 对于这个视图控制器,您可以创建UIViewController的子类或UIKit框架为管理特定类型的视图提供的视图控制器类的子类。 对于表视图,这个视图控制器类是UITableViewController 。 对于显示反映数据层次内的级别的表视图序列的导航控制器,您需要为每个表视图创建一个单独的定制表视图控制器。

The UIViewController class includes methods that let view controllers access and set the navigation items displayed in the navigation bar for the currently displayed table view. This class also declares a title property through which you can set the title of the navigation bar for the current table view.

UIViewController类包含一些方法,可让视图控制器访问和设置当前显示的表视图的导航栏中显示的导航项目。 这个类也声明了一个title 属性, 通过它你可以为当前表格视图设置导航栏的标题。

Table View Controllers

Although you could manage a table view using a direct subclass of UIViewController, you save yourself a lot of work if instead you subclass UITableViewController. The UITableViewController class takes care of many of the details you would have to implement if you created a direct subclass of UIViewController to manage a table view.

尽管您可以使用UIViewController的直接子类来管理表视图,但如果您是UITableViewController子类,则可以节省大量工作。 如果您创建了UIViewController的直接子类来管理表视图,则UITableViewController类负责处理许多必须实现的细节。

The recommended way to create a table view controller is to specify it in a storyboard. The associated table view is loaded from the storyboard, along with the table view’s attributes, size, and autoresizing characteristics. The table view controller sets itself as the data source and the delegate of the table view.

推荐的创建表格视图控制器的方法是在故事板中指定它。 关联的表格视图是从故事板加载的,以及表格视图的属性,大小和自动调整特性。 表视图控制器将自己设置为数据源和表视图的委托。

Note: You can create a table view controller programmatically by allocating memory for it and initializing it with the initWithStyle: method, passing in either UITableViewStylePlain or UITableViewStyleGrouped for the required table view style.

注意:您可以通过编程方式创建表格视图控制器,分配内存和使用initWithStyle:方法初始化,为所需的表视图样式传递UITableViewStylePlain或UITableViewStyleGrouped 。

When the table view is about to appear for the first time, the table view controller sends reloadData to the table view, which prompts it to request data from its data source. The data source tells the table view how many sections and rows per section it wants, and then gives the table view the data to display in each row. This process is described in Creating and Configuring a Table View.

当表视图即将首次出现时,表视图控制器将reloadData发送到表视图,该视图会提示它从其数据源请求数据。 数据源告诉表视图每个部分有多少section和row,然后给出表格视图显示在每行中的数据。 创建和配置表视图中介绍了此过程。

The UITableViewController class also performs other common tasks. It clears selections when the table view is about to be displayed and flashes the scroll indicators when the table finishes displaying. In addition, it responds properly when users tap the Edit button by putting the table view into editing mode (or taking it out of editing mode if users tap Done). The class exposes one property, tableView, which gives you access to the managed table view.

UITableViewController类还执行其他常见任务。 当表格视图即将显示时,它将清除选择,并在表格完成显示时闪烁滚动指示器。 另外,当用户点击编辑按钮并将表格视图置于编辑模式时(或者如果用户点击完成,则将其从编辑模式中取出),它可以正确响应。 该类公开一个属性tableView ,它可以让您访问托管表视图。

Note: A table view controller supports inline editing of table view rows; if, for example, rows have embedded text fields in editing mode, it scrolls the row being edited above the virtual keyboard that is displayed. It also supports the NSFetchedResultsController class for managing the results returned from a Core Data fetch request.

注意:表格视图控制器支持表格视图行的内联编辑; 例如,如果行在编辑模式下嵌入了文本字段,则它会将正在编辑的行滚动到所显示的虚拟键盘上方。 它还支持NSFetchedResultsController类来管理从核心数据获取请求返回的结果。

The UITableViewController class implements the foregoing behavior by overriding loadView, viewWillAppear:, and other methods inherited from UIViewController. In your subclass of UITableViewController, you may also override these methods to acquire specialized behavior. If you do override these methods, be sure to invoke the superclass implementation of the method, usually as the first method call, to get the default behavior.

UITableViewController类通过覆盖loadView , viewWillAppear:以及从UIViewController继承的其他方法来实现上述行为。 在你的UITableViewController的子类中,你也可以重写这些方法来获得专门的行为。 如果你重写了这些方法,一定要调用该方法的超类实现,通常作为第一个方法调用来获取默认行为。

Note: You should use a UIViewController subclass rather than a subclass of UITableViewController to manage a table view if the view to be managed is composed of multiple subviews, only one of which is a table view. The default behavior of the UITableViewController class is to make the table view fill the screen between the navigation bar and the tab bar (if either are present).
If you decide to use a UIViewController subclass rather than a subclass of UITableViewController to manage a table view, you should perform a couple of the tasks mentioned above to conform to the human interface guidelines. To clear any selection in the table view before it’s displayed, implement the viewWillAppear: method to clear the selected row (if any) by calling deselectRowAtIndexPath:animated:. After the table view has been displayed, you should flash the scroll view’s scroll indicators by sending a flashScrollIndicators message to the table view; you can do this in an override of the viewDidAppear: method of UIViewController.

注意:如果要管理的视图由多个子视图组成,并且只有其中一个是表视图,则应该使用UIViewController子类而不是UITableViewController的子类来管理表视图。UITableViewController类的默认行为是使表视图填充导航栏和选项卡栏(如果存在)之间的屏幕。

如果您决定使用UIViewController子类而不是UITableViewController的子类来管理表视图,则应执行上述几项任务以符合人机界面指南。 要在显示表视图之前清除所有选择,请通过调用deselectRowAtIndexPath:animated:来实现viewWillAppear:方法以清除选定行(如果有)。 在表格视图显示之后,您应该通过向表格视图发送flashScrollIndicators消息来刷新滚动视图的滚动指示器; 你可以通过覆盖UIViewController的viewDidAppear:方法来做到这一点。

Managing Table Views in a Navigation-Based App(管理基于导航的应用程序中的表格视图)

A UITableViewController object—or any other object that assumes the roles of data source and delegate for a table view—must respond to messages sent by the table view in order to populate its rows, configure it, respond to selections, and manage editing sessions. In the rest of this document, you learn how to do these things. However, there are certain other things you need to do to ensure the proper display of a sequence of table views in a navigation-based app.

UITableViewController对象 - 或承担角色的任何其他对象,对于表视图的数据源和代理,必须对表视图发送的消息进行响应,以便填充行,配置它,响应选择和管理编辑会话。 在本文档的其余部分,您将学习如何执行这些操作。 但是,还需要执行某些其他操作以确保在基于导航的应用程序中正确显示一系列表视图。

Note: This section summarizes view-controller and navigation-controller tasks, with a focus on table views. For a thorough discussion of view controllers and navigation controllers, including the complete details of their implementation, see View Controller Programming Guide for iOS and View Controller Catalog for iOS.

注意:本部分总结了视图控制器和导航控制器任务,重点讨论表视图。 有关视图控制器和导航控制器的全面讨论,包括其实现的完整细节,请参阅适用于iOS的View Controller编程指南和适用于iOS的 View Controller Catalog

At this point, let’s assume that a table view managed by a table view controller presents a list to the user. How does the app display the next table view in the sequence?

此时,我们假设由表视图控制器管理的表视图为用户提供了一个列表。 应用程序如何在序列中显示下一个表格视图?

When a user taps a row of the table view, the table view calls the tableView:didSelectRowAtIndexPath: or tableView:accessoryButtonTappedForRowWithIndexPath: method implemented by the delegate. (That latter method is invoked if the user taps a row’s detail disclosure button.) The delegate creates the table view controller managing the next table view in the sequence, sets the data it needs to populate its table view, and pushes this new view controller onto the navigation controller’s stack of view controllers. A storyboard provides the specification that allows UIKit to perform most of this work for you.

当用户点击表视图的一行时,表视图调用委托实现的tableView:didSelectRowAtIndexPath:或tableView:accessoryButtonTappedForRowWithIndexPath:方法。(如果用户点击行的详细披露按钮,则调用后一个方法。)委托创建表视图控制器,管理序列中的下一个表视图,设置填充其表视图所需的数据,并将此新视图控制器到导航控制器的视图控制器栈上。 故事板提供了允许UIKit为您执行大部分此项工作的规范。

Storyboards represent the screens in an app and the transitions between them. The storyboard in a basic app may contain just a few screens, but a more complex app might have multiple storyboards, each of which represents a different subset of its screens. The storyboard example in Figure 3-4 presents a graphical representation of each scene, its contents, and its connections.

故事板代表应用程序中的屏幕以及它们之间的转换。 基本应用程序中的故事板可能只包含几个屏幕,但更复杂的应用程序可能包含多个故事板,每个故事板都代表其屏幕的不同子集。图3-4中的故事板示例展示了每个场景及其内容和连接的图形表示。

Figure 3-4  A storyboard with two table view controllers

A scene represents an onscreen content area that is managed by a view controller. (In the context of a storyboard, scene and view controller are synonymous terms.) The leftmost scene in the default storyboard represents a navigation controller. A navigation controller is a container view controller because, in addition to its views, it also manages a set of other view controllers. For example, the navigation controller in Figure 3-4 manages the master and detail view controllers, in addition to the navigation bar and the back button that you see when you run the app.

scene表示由视图控制器管理的屏幕上内容区域。 (在故事板中,scene和视图控制器是同义词。)默认故事板中最左边的scene表示导航控制器。 导航控制器是一个容器视图控制器,因为除了视图之外,它还管理一组其他视图控制器。 例如, 图3-4中的导航控制器除了在运行应用程序时看到的导航栏和后退按钮之外,还管理主视图控制器和详细视图控制器。

A relationship is a type of connection between scenes. In Figure 3-4, there is a relationship between the navigation controller and the master scene. In this case, the relationship represents the containment of the master and detail scenes by the navigation controller. When the app runs, the navigation controller automatically loads the master scene and displays the navigation bar at the top of the screen.

关系是场景之间的一种连接。 在图3-4中 ,导航控制器和主场景之间存在关系。 在这种情况下,该关系表示导航控制器包含主场景和细节场景。 当应用程序运行时,导航控制器会自动加载主场景,并在屏幕顶部显示导航栏。

A segue represents a transition from one scene (called the source) to the next scene (called the destination). For example, in Figure 3-4, the master scene is the source and the detail scene is the destination. When you select the Detail item in the master list, you trigger a segue from the source to the destination. In this case, the segue is a push segue, which means that the destination scene slides over the source scene from right to left. As the detail screen is revealed, a back button appears at the left end of the navigation bar, titled with the previous screen’s title (in this case, “Master”). The back button is provided automatically by the navigation controller that manages the master-detail hierarchy.

segue表示从一个场景(称为源)到下一个场景(称为目的地)的过渡。 例如,在图3-4中 ,主场景是源,细节场景是目的地。 当您在主列表中选择明细项目时,您会触发从源到目的地的分段。 在这种情况下,segue是push segue,这意味着目标场景从右向左滑过源场景。 当详细信息屏幕显示时,导航栏左端将显示一个后退按钮,标题为前一屏幕的标题(在本例中为“主”)。 后退按钮由管理主 - 细节层次结构的导航控制器自动提供。

Storyboards make it easy to pass data from one scene to another via the prepareForSegue:sender: method of the UIViewController class. This method is called when the first scene (the source) is about to transition to the next scene (the destination). The source view controller can implement prepareForSegue:sender: to perform setup tasks, such as passing information to the destination view controller about what it should display in its table view. Listing 3-1 shows one implementation of this method.

通过故事板可以轻松地通过UIViewController类的prepareForSegue:sender:方法将数据从一个场景传递到另一个场景。 当第一个场景(源)即将转换到下一个场景(目标)时调用此方法。 源视图控制器