0302--iOS之阅读View Controller Programming Guide for iOS---(一)the Role of view Controller

The Role of View Controllers                                                                     --vc扮演的角色

 

View controllers are the foundation of your app’s internal structure. Every app has at least one view controller, and most apps have several. Each view controller manages a portion of your app’s user interface as well as the interactions between that interface and the underlying data. View controllers also facilitate transitions between different parts of your user interface.

       --一个app总会有一个或者多个vc,vc负责管理一个或者一个的部分用户界面,负责用户界面与底层数据的交互,促进各个用户界面之间的转换。

Because they play such an important role in your app, view controllers are at the center of almost everything you do. The UIViewController class defines the methods and properties for managing your views, handling events, transitioning from one view controller to another, and coordinating with other parts of your app. You subclass UIViewController (or one of its subclasses) and add the custom code you need to implement your app’s behavior.

       --vc占据你开发app的大部分工作,vc定义了一些方法属性是用于管理你的views、事件、vc的切换、app的其余部分的协调的。所以你只需要子类化vc,并在子类中设计你的代码即可。

There are two types of view controllers:

         --下面有两种类型的vc

  • Content view controllers manage a discrete piece of your app’s content and are the main type of view controller that you create.

        --内容vc管理的是你整个app内容拆分成独立的各个部分内容,所以内容vc是你主要使用的vc

  • Container view controllers collect information from other view controllers (known as child view controllers) and present it in a way that facilitates navigation or presents the content of those view controllers differently.

        --容器vc用于收集各个子vc的信息,管理和维护子vc之间的切换和展示。

Most apps are a mixture of both types of view controllers.

       绝大多数app都同时包含上面两种vc

 

 

View Management                                                                                        --视图的管理

 

The most important role of a view controller is to manage a hierarchy of views. Every view controller has a single root view that encloses all of the view controller’s content. To that root view, you add the views you need to display your content. Figure 1-1 illustrates the built-in relationship between the view controller and its views. The view controller always has a reference to its root view and each view has strong references to its subviews.

         --vc一个最重要的功能就是管理一个视图层次。每一个vc都有一个根view,根view包含了该vc的所有内容,根view也是你添加你设计的view的场所。vc始终保持着根view的引用,而父子view之间也有强引用。

Figure 1-1Relationship between a view controller and its views

             --vc和它的views们的关系图

0302--iOS之阅读View Controller Programming Guide for iOS---(一)the Role of view Controller

Note

It is common practice to use outlets to access other views in your view controller’s view hierarchy. Because a view controller manages the content of all its views, outlets let you store references to the views that you need. The outlets themselves are connected to the actual view objects automatically when the views are loaded from the storyboard.

           --推荐使用outlets技术去访问你的vc的视图层次。

 

A content view controller manages all of its views by itself. A container view controller manages its own views plus the root views from one or more of its child view controllers. The container does not manage the content of its children. It manages only the root view, sizing and placing it according to the container’s design. Figure 1-2 illustrates the relationship between a split view controller and its children. The split view controller manages the overall size and position of its child views, but the child view controllers manage the actual contents of those views.

          --内容vc管理它自己的所有view,容器vc管理除了自己的所有view外,还管理所有子vc的根view。★ 但是容器vc并不管理它的子vc,而仅仅是管理子vc的根view只负责各个子vc的根view的尺寸和位置

Figure 1-2View controllers can manage content from other view controllers

                   --容器vc管理子vc的视图内容的示意图

0302--iOS之阅读View Controller Programming Guide for iOS---(一)the Role of view Controller

For information about managing your view controller’s views, see Managing View Layout. --后面章节

 

Data Marshaling                                                                                     --数据的封送处理

 

A view controller acts as an intermediary between the views it manages and the data of your app. The methods and properties of the UIViewController class let you manage the visual presentation of your app. When you subclass UIViewController, you add any variables you need to manage your data in your subclass. Adding custom variables creates a relationship like the one in Figure 1-3, where the view controller has references to your data and to the views used to present that data. Moving data back and forth between the two is your responsibility.

           --vc是view和数据之间的中介。vc的属性和方法就是为了让你管理数据在app上的显示的。所以你就要在子类化的vc中,添加你的数据,并且管理你的数据在前台和后台之间的流动。

Figure 1-3 A view controller mediates between data objects and views

           --vc在view和data之间调解的示意图

0302--iOS之阅读View Controller Programming Guide for iOS---(一)the Role of view Controller

 

You should always maintain a clean separation of responsibilities within your view controllers and data objects. Most of the logic for ensuring the integrity of your data structures belongs in the data objects themselves. The view controller might validate input coming from views and then package that input in the format that your data objects require, but you should minimize the view controller’s role in managing the actual data.

       --你要确保vc和数据之间的独立性,确保那些维护数据结构完整性的“逻辑”都在“数据对象”中进行处理。所以vc只是用于验证views传递给data对象的数据的正确性,以及格式化这些数据使符合传送要求,但是这些数据的用途是由data对象使用的,vc不应该涉及数据的真实使用。

A UIDocument object is one way to manage your data separately from your view controllers. A document object is a controller object that knows how to read and write data to persistent storage. When you subclass, you add whatever logic and methods you need to extract that data and pass it to a view controller or other parts of your app. The view controller might store a copy of any data it receives to make it easier to update views, but the document still owns the true data.

        --UIDocument(文档对象)也是一种vc和data分离的实现方式,也比较适合持久化数据。vc存储的可能是数据的copy,但是文档对象储存的一定是真实数据。

 

User Interactions                                                                               --用户交互

 

View controllers are responder objects and are capable of handling events that come down the responder chain. Although they are able to do so, view controllers rarely handle touch events directly. Instead, views usually handle their own touch events and report the results to a method of an associated delegate or target object, which is usually the view controller. So most events in a view controller are handled using delegate methods or action methods.

       --vc是一个响应者对象,所以它可以响应从响应者链传递下来的事件。但vc一般不直接处理事件,而是交给view来处理,虽然view的事件代理一般也是vc,看起来也是vc在处理事件,但代理可以不是当前vc的。所以,vc处理事件的时候,一般时是用事件代理协议里面的方法。

For more information about implementing action methods in your view controller, see Handling User Interactions. For information about handling other types of events, see Event Handling Guide for iOS.  --后面章节

 

Resource Management                                                                                                          --资源管理

 

A view controller assumes all responsibility for its views and any objects that it creates. The UIViewController class handles most aspects of view management automatically. For example, UIKit automatically releases any view-related resources that are no longer needed. In your UIViewController subclasses, you are responsible for managing any objects you create explicitly.

         --vc为它所创建的view和其他对象承担所有责任。UIKit会自动释放任何不再需要的与视图相关的资源。所以在UIViewControler子类中,您只需负责管理显式创建的你的对象。

When the available free memory is running low, UIKit asks apps to free up any resources that they no longer need. One way it does this is by calling the didReceiveMemoryWarning method of your view controllers. Use that method to remove references to objects that you no longer need or can recreate easily later. For example, you might use that method to remove cached data. It is important to release as much memory as you can when a low-memory condition occurs. Apps that consume too much memory may be terminated outright by the system to recover memory.

          --当内存过低时,UIKit会自动调用vc的didReceiveMemoryWarning方法,所以你可以在子类中复写该方法,做相关的内存处理。

 

Adaptivity                                                                                                            --自适应性

 

View controllers are responsible for the presentation of their views and for adapting that presentation to match the underlying environment. Every iOS app should be able to run on iPad and on several different sizes of iPhone. Rather than provide different view controllers and view hierarchies for each device, it is simpler to use a single view controller that adapts its views to the changing space requirements.

          --vc负责其视图的表示,并调整该视图的表示以匹配底层环境。所以一个vc是兼容ipad和iphone的各种尺寸的,并不需定制。

In iOS, view controllers need to handle coarse-grained changes and fine-grained changes. Coarse-grained changes happen when a view controller’s traits change. Traits are attributes that describe the overall environment, such as the display scale. Two of the most important traits are the view controller’s horizontal and vertical size classes, which indicate how much space the view controller has in the given dimension. You can use size class changes to change the way you lay out your views, as shown in Figure 1-4. When the horizontal size class is regular, the view controller takes advantage of the extra horizontal space to arrange its content. When the horizontal size class is compact, the view controller arranges its content vertically.

          --在iOS中,vc需要处理“粗粒度变化”和“细粒度变化”。粗粒度的变化发生在视图控制器的“特征”改变时。而vc的特征是描述整个环境的属性的,例如显示范围。其中最重要的两个特征就是垂直和水平方向的尺寸类,他们用于说明在某维度下,vc有多少可用的空间。vc会根据水平类的风格来自动排列视图,如常规型风格就水平排列,紧凑型就垂直排列。

Figure 1-4  Adapting views to size class changes

                  --vc自适应尺寸类的改变。

0302--iOS之阅读View Controller Programming Guide for iOS---(一)the Role of view Controller

Within a given size class, it is possible for more fine-grained size changes to occur at any time. When the user rotates an iPhone from portrait to landscape, the size class might not change but the screen dimensions usually change. When you use Auto Layout, UIKit automatically adjusts the size and position of views to match the new dimensions. View controllers can make additional adjustments as needed.

      --在给定的size类中,随时都可能发生 细粒度的大小(可能性大)变化。当用户将iPhone从纵向旋转到横向时,尺寸类可能不会改变,但屏幕尺寸通常会改变。当你使用自动布局时,UIKit会自动调整视图的大小和位置以匹配新的尺寸。vc也可以根据需要进行额外的调整。

For more information about adaptivity, see The Adaptive Model.

 

 

The View Controller Hierarchy                                 --vc的层次结构

 

 

The relationships among your app’s view controllers define the behaviors required of each view controller. UIKit expects you to use view controllers in prescribed ways. Maintaining the proper view controller relationships ensures that automatic behaviors are delivered to the correct view controllers when they are needed. If you break the prescribed containment and presentation relationships, portions of your app will stop behaving as expected.

         --app中各个vc之间的关系,实际也代表了各个vc所需要的行为。所以你用按照规定来使用vc,这样才不会影响vc之间的一些自动化行为。

 

The Root View Controller                                                                             --根vc

 

The root view controller is the anchor of the view controller hierarchy. Every window has exactly one root view controller whose content fills that window. The root view controller defines the initial content seen by the user. Figure 2-1 shows the relationship between the root view controller and the window. Because the window has no visible content of its own, the view controller’s view provides all of the content.

            --根vc是vc层次的锚点。根vc的view是填满整个window的。window是没有可见的视图内容的,只是提供了一个舞台给vc使用。

Figure 2-1 The root view controller

                  --根vc与window之间的关系。

0302--iOS之阅读View Controller Programming Guide for iOS---(一)the Role of view Controller

The root view controller is accessible from the rootViewController property of the UIWindow object. When you use storyboards to configure your view controllers, UIKit sets the value of that property automatically at launch time. For windows you create programmatically, you must set the root view controller yourself.

         --根vc的引用绑定在UIWindow的rootViewController属性上。

 

 

Container View Controllers                                                                        --容器vc

 

Container view controllers let you assemble sophisticated interfaces from more manageable and reusable pieces. A container view controller mixes the content of one or more child view controllers together with optional custom views to create its final interface. For example, a UINavigationController object displays the content from a child view controller together with a navigation bar and optional toolbar, which are managed by the navigation controller. UIKit includes several container view controllers, including UINavigationController, UISplitViewController, and UIPageViewController.

          --容器vc使您可以将 更易于管理和可重用的部件 组装成复杂的用户界面。

A container view controller’s view always fills the space given to it. Container view controllers are often installed as root view controllers in a window (as shown in Figure 2-2), but they can also be presented modally or installed as children of other containers. The container is responsible for positioning its child views appropriately. In the figure, the container places the two child views side by side. Although it depends on the container interface, child view controllers may have minimal knowledge of the container and any sibling view controllers.

          --容器vc一般是window的根vc,但也可以是其他vc的子vc。容器中子vc的view只掌握很少的有关于容器或者兄弟vc的信息。

Figure 2-2 A container acting as the root view controller

            --扮演根vc的容器vc

0302--iOS之阅读View Controller Programming Guide for iOS---(一)the Role of view Controller

Because a container view controller manages its children, UIKit defines rules for how you set up those children in custom containers. For detailed information about how to create a custom container view controller, see Implementing a Container View Controller.

            --UIKit为自定义容器vc设定了一些规则,具体看超链接。

 

 

Presented View Controllers                                                                -- 显示vc的内容      

                            

Presenting a view controller replaces the current view controller’s contents with those of a new one, usually hiding the previous view controller’s contents. Presentations are most often used for displaying new content modally. For example, you might present a view controller to gather input from the user. You can also use them as a general building block for your app’s interface.

           --显示当前vc的内容,通常是通过隐藏上一个vc的内容来实现的。vc的展示一般是模态的。也可非模态。

When you present a view controller, UIKit creates a relationship between the presenting view controller and the presented view controller, as shown in Figure 2-3. (There is also a reverse relationship from the presented view controller back to its presenting view controller.) These relationships form part of the view controller hierarchy and are a way to locate other view controllers at runtime.

          --当你展示一个vc时,UIKit就会在当前展示vc和前任vc之间建立一种关系。也可以是前任到现任的关系。这些关系构成vc层次结构的一部分,是在运行时定位其他vc的一种方法。

Figure 2-3 Presented view controllers

             --vc的展示的前后任关系

0302--iOS之阅读View Controller Programming Guide for iOS---(一)the Role of view Controller

When container view controllers are involved, UIKit may modify the presentation chain to simplify the code you have to write. Different presentation styles have different rules for how they appear onscreen—for example, a full-screen presentation always covers the entire screen. When you present a view controller, UIKit looks for a view controller that provides a suitable context for the presentation. In many cases, UIKit chooses the nearest container view controller but it might also choose the window’s root view controller. In some cases, you can also tell UIKit which view controller defines the presentation context and should handle the presentation.

           --当涉及到容器视图控制器时,UIKit可能会修改“表示链”来简化你必须写的代码。不同的演示风格对它们在屏幕上的显示方式有不同的规则。当您呈现vc时,UIKit会查找为演示提供 合适上下文 的vc。在许多情况下,UIKit会选择最近的vc,但它也可能选择window的vc。在某些情况下,你也可以告诉UIKit哪个vc定义了 “演示的上下文” 并且处理  演示。

Figure 2-4 shows why containers usually provide the context for a presentation. When performing a full-screen presentation, the new view controller needs to cover the entire screen. Rather than requiring the child to know the bounds of its container, the container decides whether to handle the presentation. Because the navigation controller in the example covers the entire screen, it acts as the presenting view controller and initiates the presentation.

          --容器的子vc并不需要知道演示的边界,而是由容器vc来决定如何处理演示。容器vc提供了演示的上下文。

Figure 2-4A container and a presented view controller

0302--iOS之阅读View Controller Programming Guide for iOS---(一)the Role of view Controller

For information about presentations, see The Presentation and Transition Process.   --后面章节

 

 

Design Tips                                                                       --设计vc的tips 

 

View controllers are an essential tool for apps running on iOS, and the view controller infrastructure of UIKit makes it easy to create sophisticated interfaces without writing a lot of code. When implementing your own view controllers, use the following tips and guidelines to ensure that you are not doing things that might interfere with the natural behavior expected by the system.

          --遵循下面一些提示,可以让你在设计vc时没有违反系统提供的行为。

 

Use System-Supplied View Controllers Whenever Possible         --尽可能使用系统提供的vc

 

Many iOS frameworks define view controllers that you can use as-is in your apps. Using these system-supplied view controllers saves time for you and ensures a consistent experience for the user.

         --使用系统提供的vc可以保证客户的体验一致性。

Most system view controllers are designed for specific tasks. Some view controllers provide access to user data such as contacts. Others might provide access to hardware or provide specially tuned interfaces for managing media. For example, the UIImagePickerController class in UIKit displays a standard interface for capturing pictures and video and for accessing the user’s camera roll.

           --系统提供的vc性能更好,系统提供的vc是针对于某种执行任务而设计的。

Before you create your own custom view controller, look at the existing frameworks to see if a view controller already exists for the task you want to perform.

            --在你自定义vc之前,先看看系统有没有合适的vc供你使用。

  • The UIKit framework provides view controllers for displaying alerts, taking pictures and video, and managing files on iCloud. UIKit also defines many standard container view controllers that you can use to organize your content.

         --UIKit提供了在icloud上管理资源的vc,也提供了标准的容器vc

  • The GameKit framework provides view controllers for matching players and for managing leaderboards, achievements, and other game features.

           --GameKit提供了与游戏相关的vc

  • The Address Book UI framework provides view controllers for displaying and picking contact information.

             --Address Book UI framework通信录框架提供了联系人相关的vc

  • The MediaPlayer framework provides view controllers for playing and managing video, and for choosing media assets from the user’s library.

         --MediaPlayer框架提供了管理音视频的vc

  • The EventKit UI framework provides view controllers for displaying and editing the user’s calendar data.

         --EventKit框架提供了与客户日程相关的vc

  • The GLKit framework provides a view controller for managing an OpenGL rendering surface.

        --GLKit框架提供了用OpenGL技术渲染表面的vc

  • The Multipeer Connectivity framework provides view controllers for detecting other users and inviting them to connect.

        --多点连接框架提供了vc来检测其他用户并邀请他们连接。

  • The Message UI framework provides view controllers for composing emails and SMS messages.

        --Message UI框架提供了用于组合电子邮件和SMS消息的vc。

  • The PassKit framework provides view controllers for displaying passes and adding them to Passbook.

        --PassKit框架提供了用于显示通行证并将其添加到Passbook的视图控制器。

  • The Social framework provides view controllers for composing messages for Twitter, Facebook, and other social media sites.

        --社交框架提供的视图控制器,用于为Twitter、Facebook和其他社交媒体站点编写消息

  • The AVFoundation framework provides a view controller for displaying media assets.

        --AVFoundation框架提供的vc用来显示多媒体资源。

Important

Never modify the view hierarchy of system-provided view controllers. Each view controller owns its view hierarchy and is responsible for maintaining the integrity of that hierarchy. Making changes might introduce bugs into your code or prevent the owning view controller from operating correctly. In the case of system view controllers, always rely on the publicly available methods and properties of the view controller to make all modifications.

        --用于不要修改系统提供的vc层次结构。每个vc拥有自身的视图层次结构,并负责维护该层次结构的完整性。对于系统vc,你应该经常依赖于vc的公共可用方法和属性来进行所有修改。

For information about using a specific view controller, see the reference documentation for the corresponding framework.

 

Make Each View Controller an Island                                              --将每一个vc视作一个小岛 

View controllers should always be self-contained objects. No view controller should have knowledge about the internal workings or view hierarchy of another view controller. In cases where two view controllers need to communicate or pass data back and forth, they should always do so using explicitly defined public interfaces.

        --每一个vc都应该是一个自包含的对象,也就是说每一个vc都不应该去知道其他view的内部工作方式,也不应该去了解其他vc的层次结构。如果两个vc之间需要进行通信,那么它们应该使用共同的第三者接口进行通信,而不能直接通信。

The delegation design pattern is frequently used to manage communication between view controllers. With delegation, one object defines a protocol for communicating with an associated delegate object, which is any object that conforms to the protocol. The exact type of the delegate object is unimportant. All that matters is that it implements the methods of the protocol.

         --委托者设计模式 是两个vc进行通信的设计模式。也就是一个vc定义了协议,指用遵循了该协议的对象才能与该vc进行通信。遵守了该协议的对象也被叫做(被)委托对象。主要是通过协议里面的方法进行通信的,可以看一下 观察者设计模式 辅助你理解。

 

 

Use the Root View Only as a Container for Other Views                --根view仅仅充当容器就够了

 

Use the root view of your view controller solely as a container for the rest of your content. Using the root view as a container gives all of your views a common parent view, which makes many layout operations simpler. Many Auto Layout constraints require a common parent view to lay out the views properly.

          --根view仅仅充当其他view的容器的话,可以使你的布局代码变得简单。许多自动布局的规则也要求各个view之间需要一个共同的父view。

 

Know Where Your Data Lives                                              --必须知道你的数据存放在哪里

 

In the model-view-controller design pattern, a view controller’s role is to facilitate the movement of data between your model objects and your view objects. A view controller might store some data in temporary variables and perform some validation, but its main responsibility is to ensure that its views contain accurate information. Your data objects are responsible for managing the actual data and for ensuring the overall integrity of that data.

          --在mvc模式中,vc的职责就是促进数据在model和view之间的交互,view可以直接查询model的数据,但不具有修改的权限。vc的职责就是保证view得到的数据是准确的。model即data对象,必须保证真实数据的完整性。

An example of the separation of data and interface exists in the relationship between the UIDocument and UIViewController classes. Specifically, no default relationship exists between the two. A UIDocument object coordinates the loading and saving of data, while a UIViewController object coordinates the display of views onscreen. If you create a relationship between the two objects, remember that the view controller should only cache information from the document for efficiency. The actual data still belongs to the document object.

         --UIDocument类和UIViewCotroller类很好地体现了数据与界面分离的关系。UIDocument负责数据的加载和保存,而VC则协调数据在屏幕上的展示。vc应该只缓存来自UIDocument的信息。实际数据仍然属于document对象。

 

Adapt to Changes                                                                                   --vc适应iPhone机型的变化

Apps can run on a variety of iOS devices, and view controllers are designed to adapt to different-sized screens on those devices. Rather than use separate view controllers to manage content on different screens, use the built-in adaptivity support to respond to size and size class changes in your view controllers. The notifications sent by UIKit give you the opportunity to make both large-scale and small-scale changes to your user interface without having to change the rest of your view controller code.

        使用vc内建的自适应性来适应不同机型的屏幕尺寸变化,这样就不需要为每一种机型创建特定的vc

For more information about handling adaptivity changes, see The Adaptive Model.     --后面章节