0302--iOS之阅读View Controller Programming Guide for iOS---(二)View Controller Definition

 

Defining Your Subclass                                                                   --定义你的子类vc

 

You use custom subclasses of UIViewController to present your app’s content. Most custom view controllers are content view controllers—that is, they own all of their views and are responsible for the data in those views. By contrast, a container view controller does not own all of its views; some of its views are managed by other view controllers. Most of the steps for defining content and container view controllers are the same and are discussed in the sections that follow.

            --一般来说你都是通过子类化vc来展示你的app的内容的,所以你使用最多的也都是内容vc,内容vc负责管理它自己的views和数据。然而,容器vc是不曾拥有自己的views的。一些vc是通过其他vc来管理它自己的views的。定义内容或容器vc的大多数步骤是相同的,将在下一节中讨论。

For content view controllers, the most common parent classes are as follows:

       --常见的内容vc父类:

          --列表vc

          --集合vc

          --vc

For container view controllers, the parent class depends on whether you are modifying an existing container class or creating your own. For existing containers, choose whichever view controller class you want to modify. For new container view controllers, you usually subclass UIViewController. For additional information about creating a container view controller, see Implementing a Container View Controller.

          --对于容器vc,你可以选择系统现有的,也可以通过子类化vc来自定义一个。

 

Defining Your UI                                                                                      --定义你的用户界面

 

Define the UI for your view controller visually using storyboard files in Xcode. Although you can also create your UI programmatically, storyboards are an excellent way to visualize your view controller’s content and customize your view hierarchy (as needed) for different environments. Building your UI visually lets you make changes quickly and lets you see the results without having to build and run your app.

            --推荐使用IB搭建vc的UI,形象生动效率高

Figure 4-1 shows an example of a storyboard. Each of the rectangular areas represents a view controller and its associated views. The arrows between view controllers are the view controller relationships and segues. Relationships connect a container view controller to its child view controllers. Segues let you navigate between view controllers in your interface.

            --下图展示了storyboard搭建vc的实例。其中的每一个矩形代表了一个vc和它的views们。图中的两个vc之间的箭头表示一个segue,segue用于vc之间的导航。

Figure 4-1 A storyboard holds a set of view controllers and views

              --包含了一系列vc和views的storyboard

0302--iOS之阅读View Controller Programming Guide for iOS---(二)View Controller Definition

Each new project has a main storyboard that typically contains one or more view controllers already. You can add new view controllers to your storyboard by dragging them from the library to your canvas. New view controllers do not have an associated class initially, so you must assign one using the Identity inspector.

            --每一个项目都包含了一个主故事板,这个主故事板通常包含若干个已存在的vc。你可以通过从库里面拖曳一个vc到画布中,这样就相当于在storyboard里添加vc了。此时故事板中的vc还没有和代码中的vc类绑定,你需要通过xcode的标识检查器(一个xcode的窗口界面)进行相关配置才可以。

Use the storyboard editor to do the following:

             --故事板可以执行以下的操作:

  • Add, arrange, and configure the views for a view controller.

          --添加、排列、配置vc中的views

           --使用outlet关键字连接vc的方法(属性)的代码。

  • Create relationships and segues between your view controllers; see Using Segues.

              --使用segues链接两个vc之间的关系

              --根据尺寸大小类自定义views及其布局

  • Add gesture recognizers to handle user interactions with views; see Event Handling Guide for iOS.

             --添加手势识别器来处理views的互动

If you are new to using storyboards to build your interface, you can find step-by-step instructions for creating a storyboard-based interface in Start Developing iOS Apps Today (Retired).

            --对于stroyboard的新手,建议看超链接的教程。

 

 

Handling User Interactions                                                                                   --处理用户交互

 

An app’s responder objects process incoming events and take appropriate actions. Although view controllers are responder objects, they rarely process touch events directly. Instead, view controllers typically handle events in the following ways.

          --虽然vc是响应者对象,当时它一般不直接处理事件,而是用以下的方式处理事件:

  • View controllers define action methods for handling higher-level events. Action methods respond to:

    • --VC一般用来定义处理高级事件的动作方法,而这些动作方法一般作以下用途:

    • Specific actions. Controls and some views call an action method to report specific interactions.

    •        --响应具体的动作。控件和views通过调用动作方法来报告具体的交互动作。

    • Gesture recognizers. Gesture recognizers call an action method to report the current status of a gesture. Use your view controller to process status changes or respond to the completed gesture.

    •        --响应手势识别器。手势识别器调用一个方法来报告当前手势的状态。使用vc来处理手势状态的改变,或响应手势的完成状态

  • View controllers observe notifications sent by the system or other objects. Notifications report changes and are a way for the view controller to update its state.

          --VC可以订阅系统或者其他对象发出来的通知。通知是一种报告vc状态改变的方式,也是vc更新状态改变的一种方式。

  • View controllers act as a data source or delegate for another object. View controllers are often used to manage the data for tables, and collection views. You can also use them as a delegate for an object such as a CLLocationManager object, which sends updated location values to its delegate.

        --vc可以充当一个数据源,也可以充当其他对象的委托。vc经常用来管理列表、集合视图的数据。

Responding to events often involves updating the content of views, which requires having references to those views. Your view controller is a good place to define outlets for any views that you need to modify later. Declare your outlets as properties using the syntax shown in Listing 4-1. The custom class in the listing defines two outlets (designated by the IBOutlet keyword) and a single action method (designated by the IBAction return type). The outlets store references to a button and a text field in the storyboard, while the action method responds to taps in the button.

        --在下面的代码中,outlet关键字在storyboard中存储了一个按钮和文本框,而动作方法(IBAction)则用于响应按钮上的点击事件

 

Listing 4-1 Defining outlets and actions in a view controller class

         --在vc代码中定义outlet和动作方法。

  1. @interface MyViewController : UIViewController
  2. @property (weak, nonatomic) IBOutlet UIButton *myButton;
  3. @property (weak, nonatomic) IBOutlet UITextField *myTextField;
  4.  
  5. - (IBAction)myButtonAction:(id)sender;
  6.  
  7. @end
  1. class MyViewController: UIViewController {
  2. @IBOutlet weak var myButton : UIButton!
  3. @IBOutlet weak var myTextField : UITextField!
  4.  
  5. @IBAction func myButtonAction(sender: id)
  6. }

In your storyboard, remember to connect your view controller’s outlets and actions to the corresponding views. Connecting outlets and actions in your storyboard file ensures that they are configured when the views are loaded. For information about how to create outlet and action connections in Interface Builder, see Interface Builder Connections Help. For information about how to handle events in your app, see Event Handling Guide for iOS.

          --在你的storyboard中,记得将你的outlet、action与相应的view进行链接。

 

 

Displaying Your Views at Runtime                                     --在运行期间展示你的views

 

Storyboards make the process of loading and displaying your view controller’s views very simple. UIKit automatically loads views from your storyboard file when they are needed. As part of the loading process, UIKit performs the following sequence of tasks:

        --storyboard会使得你展示vc的工作变得简单。UIKit会按需加载storyboard中的view。在加载过程中,UIKit执行以下任务队列:

        1、Instantiates views using the information in your storyboard file.

             --使用storyboard中的文件的信息初始化view

        2、Connects all outlets and actions.

             --链接所有的outlet和action

        3、Assigns the root view to the view controller’s view property.

             --将根view分配给vc的view属性

        4、Calls the view controller’s awakeFromNib method.

              When this method is called, the view controller’s trait collection is empty and views may not be in their final positions.

              --调用vc的awakeFromNib方法,该方法被调用时,vc的特征组合是空的,所以vc的views不一定在它的最终位置

        5、Calls the view controller’s viewDidLoad method.

              Use this method to add or remove views, modify layout constraints, and load data for your views.

              --调用vc的viewDidLoad方法,所以vc可以使用该方法来添加移除view,修改布局约束、为views加载数据。

 

Before displaying a view controller’s views onscreen, UIKit gives you some additional chances to prepare those views before and after they are onscreen. Specifically, UIKit performs the following sequence of tasks:

       --在vc的views展示在手机屏幕上之前,UIKit会给你机会在屏幕展示之前或者之后准备这些views。具体来说,UIKit会执行以下的任务队列:

        1、Calls the view controller’s viewWillAppear: method to let it know that its views are about to appear onscreen.

                --调用vc的viewWillAppear方法,所以vc可以通过这个方法知道它的view将要出现在屏幕上

        2、Updates the layout of the views.

                --更新view的布局

        3、Displays the views onscreen.

                --在屏幕上展示view

        4、Calls the viewDidAppear: method when the views are onscreen.

               --调用vc的viewDisAppear,所以vc可以通过该方法知道view已经出现在屏幕上了。

When you add, remove, or modify the size or position of views, remember to add and remove any constraints that apply to those views. Making layout-related changes to your view hierarchy causes UIKit to mark the layout as dirty. During the next update cycle, the layout engine computes the size and position of views using the current layout constraints and applies those changes to the view hierarchy.

          --操作view的时候,记得连view的约束也一起操作。view层次发生与布局相关的变化时,UIKit会把此前的布局标记为脏布局,下一次布局更新周期中,布局引擎就会重新计算布局信息,并且使用当前布局信息进行布局。也就是布局的改变会在下一次布局更新周期中得以实施。

For information about how to create views without using storyboards, see the view management information in UIViewController Class Reference.

         不实用storyboard来创建view的方法,参考超链接。

 

 

Managing View Layout                                                                       --管理view的布局

 

When the size and position of views changes, UIKit updates the layout information for your view hierarchy. For views configured using Auto Layout, UIKit engages the Auto Layout engine and uses it to update the layout according to the current constraints. UIKit also lets other interested objects, such as the active presentation controller, know abut the layout changes so that they can respond accordingly.

            --当view的位置和尺寸发生变化时,UIKit就会更新视图层的布局信息。对于使用自动布局配置的视图,UIKit使用自动布局引擎,并根据当前的约束使用它来更新布局。UIKit还让其他感兴趣的对象,比如活动表示控制器,知道布局的变化,这样它们就可以相应地做出响应。

During the layout process, UIKit notifies you at several points so that you can perform additional layout-related tasks. Use these notifications to modify your layout constraints or to make final tweaks to the layout after the layout constraints have been applied. During the layout process, UIKit does the following for each affected view controller:

             --在布局过程中,UIKit在几个点上通知你,这样你可以执行额外的与布局相关的任务。你可以使用这些通知来修改布局约束,或在应用布局约束之后 对布局进行最后的调整。在布局过程中,UIKit为每个受影响的vc做以下操作:

        1、Updates the trait collections of the view controller and its views, as needed; see When Do Trait and Size Changes Happen?

             --根据需要,更新vc的特征集以及views

        2、Calls the view controller’s viewWillLayoutSubviews method.

            --调用vc的viewWillLayoutSubviews方法

        3、Calls the containerViewWillLayoutSubviews method of the current UIPresentationController object.

             --调用当前展示的vc的containerViewWillLayoutSubviews方法

        4、Calls the layoutSubviews method of view controller’s root view.

               --调用vc根view的layoutSubviews方法

              The default implementation of this method computes the new layout information using the available constraints.

              The method then traverses the view hierarchy and calls layoutSubviews for each subview.

             --layoutSubviews方法默认根据约束计算布局信息,然后遍历视图层次并调用各个子view的layoutSubviews方法。

        5、Applies the computed layout information to the views.

             --在view上应用计算好了的布局信息

        6、Calls the view controller’s viewDidLayoutSubviews method.

             --调用vc的viewDidLayoutSubviews方法

        7、Calls the containerViewDidLayoutSubviews method of the current UIPresentationController object.

             --调用当前展示的vc的containerViewWillLayoutSubviews方法

 

View controllers can use the viewWillLayoutSubviews and viewDidLayoutSubviews methods to perform additional updates that might impact the layout process. Before layout, you might add or remove views, update the size or position of views, update constraints, or update other view-related properties. After layout, you might reload table data, update the content of other views, or make final adjustments to the size and position of views.

         --vc可以使用viewWillLayoutSubviews和viewDidLayoutSubviews方法来执行(可能影响布局过程的)额外的更新。在布局之前,您可以添加或删除视图、更新视图的大小或位置、更新约束或更新其他与视图相关的属性。布局之后,您可以重新加载表数据,更新其他视图的内容,或者对视图的大小和位置进行最后的调整。

       

Here are some tips for managing your layout effectively:

      --下面是一些有效管理布局的技巧:

  • Use Auto Layout. The constraints you create using Auto Layout are a flexible and easy way to position your content on different screen sizes.

       --使用自动布局。

  • Take advantage of the top and bottom layout guides. Laying out content to these guides ensures that your content is always visible. The position of the top layout guide factors in the height of the status bar and navigation bar. Similarly, the position of the bottom layout guide factors in the height of a tab bar or toolbar.

       --利用顶部和底部布局辅助线。顶部布局指南的位置会影响状态栏和导航栏的高度。类似地,底部布局指南的位置也会影响标签栏或工具栏的高度。

  • Remember to update constraints when adding or removing views. If you add or remove views dynamically, remember to update the corresponding constraints.

        --在添加或删除视图时,请记住更新约束。如果动态添加或删除视图,请记住更新相应的约束。

  • Remove constraints temporarily while animating your view controller’s views. When animating views using UIKit Core Animation, remove your constraints for the duration of the animations and add them back when the animations finish. Remember to update your constraints if the position or size of your views changed during the animation.

       --在动画化 vc的视图时 请临时删除约束。当使用UIKit Core Animation制作视图动画时,在动画的持续时间内移除你的约束,并在动画结束时将它们添加回来。如果在动画期间视图的位置或大小发生变化,请记住更新约束。

For information about presentation controllers and the role they play in the view controller architecture, see The Presentation and Transition Process.

         --有关展示vc及其在视图控制器体系结构中扮演的角色的信息,请参见超链接

    

 

Managing Memory Efficiently                                                             --高效管理内存

 

Although most aspects of memory allocation are for you to decide, Table 4-1 lists the methods of UIViewController where you are most likely to allocate or deallocate memory. Most deallocations involve removing strong references to objects. To remove a strong reference to an object, set properties and variables pointing to that object to nil.

         --尽管内存分配的大多数方面由您来决定,表4-1列出了UIViewController中最可能分配或释放内存的方法。大多数内存释放的地方都涉及了删除对象的强引用。要删除对象的强引用,请将指向该对象的属性和变量设置为nil。

 

 

Table 4-1Places to allocate and deallocate memory --分配和释放内存的地方

Task

Methods

Discussion

Allocate critical data structures required by your view controller. --在 分配(vc所需的)关键数据结构时。

Initialization methods

Your custom initialization method (whether it is named init or something else) is always responsible for putting your view controller object into a known good state. Use these methods to allocate whatever data structures are needed to ensure proper operation. --您自定义初始化方法(无论它的名称是init还是其他什么)总是负责将vc对象置于已知的良好状态。所以你要使用这些方法来分配任何必要的数据结构,以确保正确的操作。

Allocate or load data to be displayed in your view.  --在分配或加载要在视图中显示的数据 时

viewDidLoad

Use the viewDidLoad method to load any data objects you intend to display. By the time this method is called, your view objects are guaranteed to exist and to be in a known good state. --使用viewDidLoad方法来加载要显示的任何数据对象。在此方法被调用时,您的视图对象已确保存在并处于已知的良好状态。

Respond to low-memory notifications.  --在响应 低内存通知 时

didReceiveMemoryWarning

Use this method to deallocate all noncritical objects associated with your view controller. Deallocate as much memory as you can.  --使用此方法释放与视图控制器关联的所有非关键对象。释放尽可能多的内存。

Release critical data structures required by your view controller.--在释放(vc所需的)关键数据结构时。

dealloc

Override this method only to perform any last-minute cleanup of your view controller class. The system automatically releases objects stored in instance variables and properties of your class, so you do not need to release those explicitly. --只在最后一刻对视图控制器类进行清理时重写此方法。系统会自动释放存储在实例变量和类属性中的对象,因此不需要显式地释放这些对象。