View and Window Architecture
Views and windows present your application’s user interface and handle the interactions with that interface. UIKit and other system frameworks provide a number of views that you can use as-is with little or no modification. You can also define custom views for places where you need to present content differently than the standard views allow.
Whether you use the system views or create your own custom views, you need to understand the infrastructure provided by the UIView
and UIWindow
classes. These classes provide sophisticated(复杂) facilities for managing the layout and presentation of views. Understanding how those facilities work is important for making sure your views behave appropriately when changes occur in your application.
View Architecture Fundamentals
Most of the things you might want to do visually are done with view objects—instances of the UIView
class. A view object defines a rectangular region on the screen and handles the drawing and touch events in that region. A view can also act as a parent for other views and coordinate the placement and sizing of those views. The UIView
class does most of the work in managing these relationships between views, but you can also customize the default behavior as needed.
Views work in conjunction(联结) with Core Animation layers to handle the rendering and animating of a view’s content. Every view in UIKit is backed by(支持) a layer object (usually an instance of the CALayer
class), which manages the backing store for the view and handles view-related animations. Most operations you perform should be through the UIView
interface. However, in situations where you need more control over the rendering or animation behavior of your view, you can perform operations through its layer instead.
To understand the relationship between views and layers, it helps to look at an example. Figure 1-1 shows the view architecture from the ViewTransitions sample application along with the relationship to the underlying Core Animation layers. The views in the application include a window (which is also a view), a generic UIView
object that acts as a container view, an image view, a toolbar for displaying controls, and a bar button item (which is not a view itself but which manages a view internally). (The actual ViewTransitions sample application includes an additional image view that is used to implement transitions. For simplicity, and because that view is usually hidden, it is not included in Figure 1-1.) Every view has a corresponding layer object that can be accessed from that view’s layer
property. (Because a bar button item is not a view, you cannot access its layer directly.) Behind those layer objects are Core Animation rendering objects and ultimately the hardware buffers used to manage the actual bits on the screen.