導航數據表視圖層次html
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.node
表格視圖經常被用來導航數據層次,並且它們很適合。在層次頂層的表格視圖列出了整體的數據類別(categories of data)。用戶選擇一行來深刻到層次的下一層。 層次的底層是一個視圖(經常是一個表格視圖)表示一個指定數據項的具體信息(好比,一個地址簿),而且可能讓用戶編輯它們。 本節講述了你如何纔可以把數據模型層次中的層映射到一連串的表格視圖中,以及描述瞭如何使用UIkit框架的功能來幫你實現這樣的基於導航的應用程序。ios
1、層次數據模型和表格視圖編程
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,屬性列表,或自定義歸檔對象。 無論使用哪一種方法,應用程序數據模型的遍歷都遵循全部基於導航應用程序都通用的模式。 數據模型有層次深度,在該層次中不一樣層的對象應該是填充一個表格視圖行的資源。數組
Note: To learn about the Core Data technology and framework, see Core Data Starting Point.session
注意:要想學習關於Core Data 技術和框架,請看Core Data Starting Point.app
一、數據模型做爲模型對象的一個層次框架
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.less
一個應用程序設計良好的因素是它的類和對象遵循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 對象,(或簡單的數組)。 一個數組可能包含其餘數組,或它能包含多個字典,字典是經過鍵來標識它們包含的內容的一種集合類型。 相反,字典能夠包含一個或多個其它集合,包括數組,集,甚至是其它字典。 正如集合嵌套在其它集合,你的數據模型能夠得到層次深度。
二、表格視圖和數據模型
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.
簡樸表格視圖的行一般跟應用程序數據模型的集合對象相綁定; 這些對象一般是數組。 數組包含了字符串或其它表格視圖能在顯示行內容時使用的元素。當你建立一個表格視圖時(「Creating and Configuring a Table View」 中描述),它當即向它的數據源請求它的尺寸---就是說,它要求區(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.
在表格視圖的數據源和委託中定義的不少方法中,表格視圖傳遞一個索引路徑來標識發生當前操做的區和行---好比,取回一行內容或縮進用戶點擊的行。 索引路徑是Foundation 框架的 NSIndexPath 的一個實例, 你可使用它來標識嵌套數組樹種的數據項。 UIKit 框架延伸了NSIndexPath ,給類添加了一個section 和一個
row 特性。數據源應該使用這些特性來映射表格視圖的一個區和行到表格視圖數據源數組中相關索引處的值。
Note: The UIKit framework extension of the NSIndexPath
class is described in NSIndexPath UIKit Additions.
注意:UIKit框架對NSIndexPath類的擴展在NSIndexPath UIKit Additions中描述。
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中的表格視圖序列中,數據層次的頂層是一個包含有四個子數組的數組, 每一個子數組包含了表明一個特殊區域的小徑(trail)對象。 當用戶選擇了這些區域中的其中一個,下個表格視圖列出被選擇數組中的小徑名稱。 當用戶選擇一個特殊的小徑,下一個表格視圖使用一個分組表格視圖描述該小徑。
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中的應用程序,讓它只包含兩個表格視圖。第一個表格視圖應該是一個以區域爲索引的小徑索引列表。第二個表格視圖顯示被選擇小徑的具體內容。
2、視圖控制器和基於導航的應用程序
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.
在iOS中UIKit 框架提供了不少視圖控制器類來管理通用用戶接口模式。 視圖控制器是從 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.
注意:本節給出了視圖控制器的一個概述,覺得本文檔中稍候討論的代碼任務提供一些背景知識。要想深度學習視圖控制器,請看View Controller Programming Guide for 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)。 它從根視圖控制器開始。 當用戶點擊了表格視圖中的一行(經常是一個詳細擴展按鈕),根視圖控制器把下一個視圖控制推送到棧。 新的視圖控制器控制的表格視圖直觀地從右邊滑入到位,而且導航欄數據項被響應的更新。 當用戶點擊導航欄中的返回按鈕, 當前的視圖控制器彈出棧。所以,導航控制器顯示視圖控制器管理的位於棧頂部的表格視圖。
Navigation controller and view controllers in a navigation-based app
圖3-2 基於導航的應用程序中的導航控制器和視圖控制器
二、導航欄
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)。
Navigation bars and common control items
圖3-3 導航欄和經常使用控件項
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屬性,經過它你能夠爲當前表格視圖設置導航欄的標題。
三、表格視圖控制器
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繼承能夠減小不少工做。UITableViewController 類 帶有不少你必需要實現的不少細節,這是你直接從UIViewController繼承來管理表格視圖所沒有的。
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 theinitWithStyle:
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消息,它促使表格視圖從它的數據源那裏請求數據。 數據源告訴表格視圖有多少區,以及每一個分區有多少行,而後給表格視圖提供數據讓其顯示每行。 該過程描述在 「Creating and Configuring a Table View.」
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 類還執行其它經常使用任務。 當表格視圖即將顯示而且當表格結束顯示滾動指示器閃爍時,它清除各個區。此外,當用戶點擊編輯按鈕時,它能正確響應用戶點擊,讓表格視圖進入編輯模式(或者退出編輯模式,若是用戶點擊Done)。UITableViewControler類有一個屬性,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.
注意:表格視圖控制器支持表格視圖行的內嵌編輯(inline editing);好比,若是在編輯模式下行中內嵌了文邊字段,它把正在編輯的行滾動到虛擬鍵盤顯示的上方。它還支持 NSFetchedResultsController 類來管理從一個Core Data fetch請求返回的結果。
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).
注意:若是所管理的視圖是由多個子視圖組成,只有其中一個是表格視圖時,你應該使用一個UIViewController子類而不是UITableViewController的子類來管理表格視圖。UITableViewController 類的默認行爲是讓表格視圖填充導航欄和標籤欄(若是其中之一有存在的話)之間的屏幕。
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子類來管理一個表格視圖,你應該遵循人性化接口設計指南執行上面提到的兩個任務。 要想在表格視圖顯示以前清除任何區(section),實現viewWillAppear: 方法經過調用deselectRowAtIndexPath:animated:方法
來清除被選中的行(若是有)。 當表格視圖已經顯示以後,你應該經過給表格視圖發送一個 flashScrollIndicators 消息來閃爍滾動視圖的滾動指示器;你能夠在重寫 UIViewController 的 viewDidAppear: 方法中完成。
四、在一個基於導航的應用程序中管理表格視圖
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對象---或任何其它兼任表格視圖數據源和委託的對象---都必須響應表格視圖發送的各類消息,以填充它的行,配置它,響應區(sections),以及管理編輯會話。 在文檔的剩餘部分,你將學習如何實現這些事情。然而,在一個基於導航的應用程序中,你確實還須要完成其它事情來確保一系列表格視圖的正確顯示。
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.
主要:本節總結了視圖控制器 和導航控制器任務,還重點講述了表格視圖。關於視圖控制器和導航控制器的詳細討論,包括實現他們的完整詳情,請看 View Controller Programming Guide for iOS 以及 View Controller Catalog for iOS.
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:
ortableView: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中的故事板例子顯示了每一個場景,它的內容,以及它的連接關係等圖形表示。
A storyboard with two table view controllers
圖 3-5 帶有兩個表格視圖控制器的故事板
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.
場景表明屏幕上的一個內容區域,它由一個視圖控制器管理。(在故事板的上下文中,場景和視圖控制器是同義詞) 故事板中最左邊的場景表明一個導航控制器。導航控制器是一個容器視圖控制器,由於除了它的視圖,它還管理一組其它視圖控制器。 好比,Figure 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中,主場景是源,詳情場景是目標。當你在主列表裏選擇了具體數據項,你就觸發了從源到目標的一個跳轉。在本例中,跳轉是一個推送跳轉,就是說目標場景從右到左滑到源場景上。當詳情屏幕顯示後,在導航欄的左邊顯示一個返回按鈕,按鈕標題是前一個屏幕的標題(在本例中是」Master「)。返回按鈕由管理master-detail層次的導航控制器自動提供。
Storyboards make it easy to pass data from one scene to another via the prepareForSegue:sender:
method of theUIViewController
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-1shows one implementation of this method.
故事板經過UIViewController類的prepareForSegue:sender:方法讓數據從一個場景傳送到另外一個場景變得簡單。該方法在當第一個場景(源)即將過渡到下一個場景(目標)時調用。源視圖控制器能夠實現prepareForSegue:sender: 方法來執行啓動任務,好比傳送信息給目標視圖控制器,讓其知道該在它的表格視圖裏顯示什麼內容。列表3-1顯示了該方法的一個實現。
Passing data to a destination view controller
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender |
{ |
if ([[segue identifier] isEqualToString:@"ShowDetails"]) { |
MyDetailViewController *detailViewController = [segue destinationViewController]; |
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow]; |
detailViewController.data = [self.dataController objectInListAtIndex:indexPath.row]; |
} |
} |
A segue represents a one-way transition from a source scene to a destination scene. One of the consequences of this design is that you can use a segue to pass data to a destination, but you can’t use a segue to send data from a destination to its source. To solve this problem, you create a delegate protocol that declares methods that the destination view controller calls when it needs to pass back some data.
推送(segue)表示從一個源場景到目標場景的一個單向過渡。所以,該設計只能讓你使用推送來傳送數據到目標場景,而不能使用推送(segue)從目標場景傳送數據到源場景。要想解決該問題,你須要建立一個委託協議,它聲明瞭目標視圖控制器在它須要回送一些數據時調用的方法。
Listing 3-2 shows one implementation of a protocol for passing data back to a source view controller.
列表 3-2 顯示了一個協議的實現,該協議用來回送數據到一個源視圖控制器。
Passing data to a source view controller
@protocol MyAddViewControllerDelegate <NSObject> |
- (void)addViewControllerDidCancel:(MyAddViewController *)controller; |
- (void)addViewControllerDidFinish:(MyAddViewController *)controller data:(NSString *)item; |
@end |
- (void)addViewControllerDidCancel:(MyAddViewController *)controller { |
[self dismissViewControllerAnimated:YES completion:NULL]; |
} |
- (void)addViewControllerDidFinish:(MyAddViewController *)controller data:(NSString *)item { |
if ([item length]) { |
[self.dataController addData:item]; |
[[self tableView] reloadData]; |
} |
[self dismissViewControllerAnimated:YES completion:NULL]; |
} |
Note: The full details of creating storyboards are described in Xcode User Guide. To learn more about using view controllers in storyboards, see View Controller Programming Guide for iOS.
注意:建立故事板的完整信息在Xcode User Guide 裏詳細描述。要想學習更多關於在故事板中使用視圖控制器的內容,請看View Controller Programming Guide for iOS.
3、基於導航應用程序的設計模式
A navigation-based app with table views should follow these design best practices:
一個帶有表格視圖的基於導航的應用程序應該遵循這些最好的設計實踐:
A view controller (typically a subclass of UITableViewController
), acting in the role of data source, populates its table view with data from an object representing a level of the data hierarchy.
視圖控制器(一般是UITableViewController 的一個子類),是數據源,從表明數據層次的一層的對象中獲取數據填充它的表格視圖。
When the table view displays a list of items, the object is typically an array. When the table view displays item detail (that is, a leaf node of the data hierarchy), the object can be a custom model object, a Core Data managed object, a dictionary, or something similar.
當表格視圖顯示一個數據項列表,對象一般是一個數組。當表格視圖顯示數據詳情時(就是數據層次中的一個葉節點),對象能夠是一個自定義模型對象,一個Core Data管理的對象,一個字典,或一些相似的對象。
The view controller stores the data it needs for populating its table view.
視圖控制器存儲了須要用來填充其表格視圖的數據。
The view controller can use this data directly for populating the table view, or it can use it to fetch or otherwise obtain the necessary data. When you design your view controller subclass, you should define a property to hold this data.
視圖控制器可使用該數據直接填充表格視圖,或它能使用它來提取或用其它方法得到必要的數據。 當你設計你的視圖控制器子類時,你應該定義一個屬性(property)來hold這些數據。
View controllers should not obtain the data for their table view through a global variable or a singleton object such as the app delegate. Such direct dependencies make your code less reusable and more difficult to test and debug.
視圖控制器不該該經過一個全局變量或一個單一對象好比應用程序委託來獲取表格視圖數據。這樣直接的依賴使你的代碼缺乏可重用性,而且更難測試和調試。
The current view controller on top of the navigation-controller stack creates the next view controller in the sequence and, before it pushes it onto the stack, sets the data that this view controller, acting as data source, needs to populate its table view.
位於導航控制器棧頂部的當前視圖控制器建立序列中的下一個視圖控制器,而且在把它推送到棧以前,設置做爲數據源的視圖控制器的數據,這些數據用來填充其表格視圖。