ViewController編程指南

View Controller是App內部結構的基礎。每個App至少含有一個View Controller,大多數會含有多個。每個View Controller管理着App用戶界面的一部分,包括這些界面間的交互以及潛在的數據。View Controller也管理不同用戶界面間的過渡。

由於在App中扮演的重要作用,View Controller的角色處於中心位置。UIViewController類定義了管理views的方法、屬性、事件處理、view controller間的過渡以及如何與App其他部分的交互方法。通常你要子類化UIViewController,添加一些自定義代碼來實現你的功能。

存在兩種View Controller:

  • Content view controller管理着app的一個單獨的內容,是創建view controller的主要類型

  • Container view controller包含若干其他view controller的信息(child view controller),根據不同的需求呈現這些view controllers。

視圖管理

View Controller最重要的角色就是管理views的繼承樹。每個view controller只含有一個root view,它包含了view controller的所有內容。對於root view,你可以向它添加你所需要的view來展現你的內容。如下圖,展示了view controller和view的內部關係。
VCPG_ControllerHierarchy_fig_1-1_2x.png

content view controller獨自管理着其下所有的views。container view controller管理着它自己的views以及其子view controller的root view。container view controller不負責管理其子view controller的內容。下圖是一個container view controller與其下子view controller間的關係:
VCPG_ContainerViewController_fig_1-2_2x.png

數據管理

view controller扮演者view和數據間的中介。UIViewController類的屬性和方法使得你能夠管理app的視覺展示。當子類化view controller時,你可以添加任何你所需要的變量。下圖展示了它們之間的關係:
VCPG_CustomSubclasses_fig_1-3_2x.png

你必須將view controller和數據對象間的職責清晰的分開。

用戶交互

view controller屬於responder對象,能夠處理傳遞下來的事件。儘管如此,view controller極少直接處理touch events。通常由views來處理自己的touch事件,並將結果報告給代理的一個方法或target對象(通常是這個view controller)。所以大多數事件都是由代理方法或actions方法來處理的。

資源管理

主要是內存資源

適配

自動調整尺寸