View Programming Guide for iOS——官方文档翻译(2.1)View Architecture Fundamentals

View Architecture Fundamentals

一、视图架构基础

Most of the things you might want to do visually are donewith view objects—instances of the UIView class.A view object defines a rectangular region on the screen and handles thedrawing and touch events in that region. A view can also act as a parent forother views and coordinate the placement and sizing of those views. TheUIViewclass does most of thework in managing these relationships between views, but you can also customizethe default behavior as needed.

大多数你可能想要做的可视化是由视图对象完成的——及UIView类的实例。视图对象在屏幕上定义了一个矩形区域,并在该区域内处理绘图和触摸事件。视图也可以充当其它视图的父视图,并为那些视图定位和定尺寸。UIView类的大部分工作是管理这些视图间关系,你也可以根据需要自定义默认行为。

Views work in conjunction with Core Animation layers tohandle the rendering and animating of a view’s content.Every view in UIKit is backed by a layer object (usually an instance of theCALayerclass), which manages the backing store for the view and handles view-related animations.Mostoperations you perform should be through theUIViewinterface. However, insituations where you need more control over the rendering or animation behaviorof your view, you can perform operations through its layer instead.

视图结合内核动画(Core Animation)层一起,来处理视图内容的渲染和动画。通过一个层对象(通常是CALayer类的一个实例),在UIKit框架里的每个视图都支持管理视图的后台存储和处理视图相关的各种动画。你执行的大多数操作应该凭借UIView接口。然而,在你需要更多的控制关于渲染(rendering)或动画视图的行为的情况下,你可以执行操作它的层来代替。

To understand the relationship between views and layers, ithelps to look at an example.Figure 1-1showsthe view architecture from the ViewTransitions sample application along withthe relationship to the underlying Core Animation layers. The views in theapplication include a window (which is also a view), a genericUIViewobject that acts as acontainer view, an image view, a toolbar for displaying controls, and a barbutton item (which is not a view itself but which manages a view internally).(The actual ViewTransitions sample application includes anadditional image view that is used to implement transitions. For simplicity,and because that view is usually hidden, it is not included inFigure 1-1.) Every view has a corresponding layerobject that can be accessed from that view’s layer property.(Because a bar button item is not a view, you cannot access its layerdirectly.) Behind those layer objects are Core Animation rendering objects andultimately the hardware buffers used to manage the actual bits on the screen.

为了理解视图和层之间的关系,看个例子更有帮助。图1-1显示了ViewTransitions示例应用中的视图结构,以及跟底层的内核动画层之间的关系。应用中的视图包含一个窗口(也是一个视图),一个通用的UIView对象,它充当容器视图(container view),一个图像视图,用于显示控件的工具栏,和一个工具栏按钮项(它本身不是一个视图,但是在内部管理了一个视图)。(实际的ViewTransitions示例应用还包含一个额外的图像视图,用来实现过渡(transitions)。因为那个视图通常是隐藏的,为简单起见没包含在图1-1里)每一个视图都有一个对应的层对象,可以从该视图的layer属性访问。(因为工具栏按钮项不是一个视图,你不能直接访问它的层)这些层对象的背后是内核动画渲染对象,最终硬件缓存(hardware buffers)用来管理屏幕上的实际位。

Figure 1-1Architecture of the views in a sample application


View Programming Guide for iOS——官方文档翻译(2.1)View Architecture Fundamentals_第1张图片

The use of Core Animation layer objects has importantimplications for performance. The actual drawing code of a view object iscalled as little as possible, and when the code is called, the results arecached by Core Animation and reused as much as possible later. Reusingalready-rendered content eliminates the expensive drawing cycle usually neededto update views.Reuse of this content is especially important during animations, where the existing content can be manipulated.Suchreuse is much less expensive than creating new content.

内核动画层对象的使用对性能有很重要的意义。视图的对象的实际绘图代码会被尽可能少的调用,当代码被调用时,结果通过内核动画缓存,并在以后尽可能多的重用。重用已经被渲染的内容减少了通常需要更新视图的昂贵的绘图周期。在动画时这个存在的内容能被操作,而且这个内容的重用是尤其重要的。这样的重用比创建新内容节省消耗。

View Hierarchies and Subview Management

1.视图层次以及子视图管理

In addition to providing its own content, a view can act asa container for other views. When one view contains another, a parent-childrelationship is created between the two views. The child view in therelationship is known as the subview and the parent view is known asthe superview. The creation of this type of relationship has implicationsfor both the visual appearance of your application and the application’s behavior.

除了提供它自己的内容,视图还能充当其它视图的容器。当一个视图包含了另一个时,在这两个视图之间就建立了父子关系。在这个关系中的子视图通常被称为子视图(subview),而父视图则被称为superview。这种类型的关系的创建对于你应用的可视化外观和应用的行为都有一定的影响。

Visually, the content of a subview obscures all or part ofthe content of its parent view. If the subview is totally opaque, then the areaoccupied by the subview completely obscures the corresponding area of theparent. If the subview is partially transparent, the content from the two viewsis blended together prior to being displayed on the screen. Each superviewstores its subviews in an ordered array and the order in that array alsoaffects the visibility of each subview. If two sibling subviews overlap eachother, the one that was added last (or was moved to the end of the subviewarray) appears on top of the other.

在视觉上,子视图的内容掩盖了全部或部分它的父视图的内容。如果子视图是完全不透明的,则子视图占据的区域完全掩盖了父视图的相应区域。如果子视图部分透明的,则两个视图的内容在显示到屏幕上之前被混合在一起。每个父视图把它们的子视图按照一定顺序存在一个数组里,该顺序也影响了每个子视图的可见性。如果两个兄弟子视图互相重叠,则后加(或被移到子视图数组的末尾的)的视图显示在前一个视图的上面。

The superview-subview relationship also impacts severalview behaviors. Changing the size of a parent view has a ripple effect that cancause the size and position of any subviews to change too. When you change thesize of a parent view, you can control the resizing behavior of each subview byconfiguring the view appropriately. Other changes that affect subviews includehiding a superview, changing a superview’s alpha (transparency), or applying amathematical transform to a superview’s coordinate system.

父子视图关系也影响了一些视图行为。改变父视图的尺寸会产生一个连锁反应,导致子视图的尺寸和位置也发生改变。当你改变父视图的尺寸时,通过适当地配置这个视图,你能够控制每个子视图调整大小的行为(resizing behavior)。其它影响子视图的改变还包括隐藏父视图,改变父视图的alpha值(透明度),或给父视图的坐标系统应用一个数学变换。

The arrangement of views in a view hierarchy alsodetermines how your application responds to events. When a touch occurs insidea specific view, the system sends an event object with the touch informationdirectly to that view for handling. However, if the view does not handle aparticular touch event, it can pass the event object along to its superview. Ifthe superview does not handle the event, it passes the event object to itssuperview, and so on up the responder chain. Specific views can also pass theevent object to an interveningresponder object,such as a view controller. If no object handles the event, it eventuallyreaches the application object, which generally discards it.

视图在视图层次里的排列也决定了应用程序如何对事件做出响应。当触摸发生在一个特定视图内部时,系统直接发送一个具有触摸信息的事件对象让其处理。然而,如果该视图没有处理特定的触摸事件,它能够向前传递事件对象到它的父视图。如果它的父视图还没有处理该事件,则把事件传递给父视图的父视图,如此这般逐级提高响应链。特定视图也可以传递事件对象给一个介于中间的响应对象,比如一个视图控制器。如果没有对象处理该事件,它最终会被传递到应用程序对象,通常由应用程序对象把它丢弃。

For more information about how to create view hierarchies,see“Creating and Managing a View Hierarchy.”

关于如何创建视图层次的更多信息,请看“Creating and Managing a View Hierarchy.”

The View Drawing Cycle

2.视图绘制周期

TheUIViewclassuses an on-demand drawing model for presenting content. When a view firstappears on the screen, the system asks it to draw its content. The systemcaptures a snapshot of this content and uses that snapshot as the view’s visualrepresentation. If you never change the view’s content, the view’s drawing codemay never be called again. The snapshot image is reused for most operationsinvolving the view. If you do change the content, you notify the system thatthe view has changed. The view then repeats the process of drawing the view andcapturing a snapshot of the new results.

UIView类使用一种按需绘制模型(on-demand drawing model)来呈现视图内容。当视图第一次出现在屏幕上时,系统要求它绘制其内容。系统捕捉该内容的快照,并使用该快照作为视图的视觉呈现(visual representation)。如果你一点也没有改变视图的内容,那视图的绘制代码可能不会再被调用。快照图片被涉及视图的大多数操作所重用。如果你对内容做了改变,你需要通知系统告诉它视图已经改变。然后视图重复绘制视图过程,并捕捉新的快照。

When the contents of your view change, you do not redrawthose changes directly. Instead, you invalidate the view using either the setNeedsDisplay or setNeedsDisplayInRect:method.These methods tell the system that the contents of the view changed and need tobe redrawn at the next opportunity. The system waits until the end of thecurrent run loop before initiating any drawing operations. This delay gives youa chance to invalidate multiple views, add or remove views from your hierarchy,hide views, resize views, and reposition views all at once. All of the changesyou make are then reflected at the same time.

当你的视图内容发生改变时,你不会直接重新绘制那些改变。你可以用setNeedsDisplay或setNeedsDisplayInRect:方法让视图无效。这些方法告诉系统视图的内容已经发生改变,需要在下次重新绘制。该系统在启动任何绘图操作之前,等待当前运行循环的结束。该延时给你一次机会,用来一次性完成废弃多个视图,从视图层次里添加或删除视图,隐藏视图,调整视图大小,重新配置视图等。所有这些你做的变化将在同一时间反映出来。

Note: Changinga view’s geometry does not automatically cause the system to redraw the view’scontent. The view’scontentModepropertydetermines how changes to the view’s geometry are interpreted. Most contentmodes stretch or reposition the existing snapshot within the view’s boundariesand do not create a new one. For more information about how content modesaffect the drawing cycle of your view, see“Content Modes.”

注意:改变视图的几何结构并不会自动导致系统重画视图内容。视图的contentMode属性确定了如何改变视图的几何解释。大多数内容模式都是在视图边界里拉伸或重新配置已经存在的快照,并不需要创建新视图内容。了解更多关于内容模式如何影响视图的绘制周期,请看“Content Modes.”

When the time comes to render your view’s content, the actual drawing process varies depending on the view and its configuration. System views typically implement private drawing methods to render their content. Those same system views often expose interfaces that you can use to configure the view’s actual appearance. For customUIViewsubclasses, you typicallyoverride the drawRect:method of your view and use that method to draw yourview’s content. There are also other ways to provide a view’s content, such assetting the contents of the underlying layer directly, but overriding thedrawRect:method is the mostcommon technique.

当开始渲染视图内容时,实际的绘图过程根据视图和它的配置而变化。系统视图通常执行私有绘图方法来渲染它们的内容。那些相同的系统视图常常暴露出接口,让你可以用来配置视图实际的外观。为了定制UIView子类,你通常重载(override)视图的drawRect:方法,并用该方法绘制视图的内容。还有其它方法来提供一个视图的内容,比如直接设置底层内容,但是重载drawRect:方法是最通用的技术。

For more information about how to draw content for customviews, see“Implementing Your Drawing Code.”

更多有关如何绘制自定义视图的内容方面的信息,请看“Implementing Your Drawing Code.”

Content Modes

3.内容模式

Each view has a content mode that controls how the viewrecycles its content in response to changes in the view’s geometry and whetherit recycles its content at all. When a view is first displayed, it renders itscontent as usual and the results are captured in an underlying bitmap. Afterthat, changes to the view’s geometry do not always cause the bitmap to berecreated. Instead, the value in thecontentModepropertydetermines whether the bitmap should be scaled to fit the new bounds or simplypinned to one corner or edge of the view.

每个视图都有一个内容模式(content model),在视图几何外形发生变化时,用来控制视图如何 回收 重用它的内容来响应视图几何外形的改变,以及是否回收重用其全部内容。当视图被第一次显示时,它跟平时一样渲染它的内容,并且结果被捕获到一个底层位图里。然后,视图几何外形的改变并不总是导致重新创建位图。相反,contentMode属性的值决定了该位图是否应该缩放来适应新的边界,或只需要简单的固定到视图的一个角落或一边。

The content mode of a view is applied whenever you do thefollowing:

视图的内容模式被应用到以下情况:

    ·Change the width or height ofthe view’sframeorboundsrectangles.

    更改视图框架或矩形边界(frameorbounds)的长度或宽度。

    ·Assign a transform thatincludes a scaling factor to the view’stransformproperty.

    给视图transform的属性分配一个变换,该变换包含一个缩放因子。

By default, thecontentModeproperty for most views is set to UIViewContentModeScaleToFill,which causes the view’s contents to be scaled to fit the new frame size.Figure 1-2shows the results that occur for somecontent modes that are available. As you can see from the figure, not allcontent modes result in the view’s bounds being filled entirely, and those thatdo might distort the view’s content.

默认时,大多数视图的内容模式属性被设为UIViewContentModeScaleToFill,该设置导致视图的内容被缩放以适应新的框架尺寸。图1-2显示了一些可用的内容模式效果。正如你在图中看到,不是所有的内容模式导致视图边界被完全填满,而且那些确实填满边界的图形可能失真(distort)。

Figure 1-2  Content mode comparisons

图1-2内容模式比较


View Programming Guide for iOS——官方文档翻译(2.1)View Architecture Fundamentals_第2张图片

Content modes are good for recycling the contents of yourview, but you can also set the content mode to the UIViewContentModeRedraw valuewhen you specifically want your custom views to redraw themselves duringscaling and resizing operations. Setting your view’s content mode to this valueforces the system to call your view’sdrawRect:method in response to geometry changes. In general, you shouldavoid using this value whenever possible, and you should certainly not use itwith the standard system views.

内容模式对于回收视图内容很好,但是你也可以设置内容模式为UIViewContentModeRedraw值,当你明确地想要你的自定义视图在缩放和大小调整操作也重新绘制时。把你的视图内容模式设置为该值强制系统在视图几何外形发生变化时调用drawRect:方法。一般来说,你应该尽可能的避免使用该值,而且确定不把它跟标准系统视图一起使用。

For more information about the available content modes,see UIView Class Reference.

更多有关可用内容模式的信息,请看UIView Class Reference.

StretchableViews

4.可拉伸视图

You can designate a portion of a view as stretchable sothat when the size of the view changes only the content in the stretchableportion is affected. You typically use stretchable areas for buttons orother views where part of the view defines a repeatable pattern. The stretchable area you specify can allow for stretching alongone or both axes of the view. Of course, when stretching a view along two axes,the edges of the view must also define a repeatable pattern to avoid anydistortion.Figure 1-3 shows how this distortion manifests itself in aview. The color from each of the view’s original pixels is replicated to fillthe corresponding area in the larger view.

你可以指明视图的一部分为可拉伸的,以便当视图的大小发生改变时,只有可拉伸部分的内容受到影响。你通常对按钮,或对定义了一个可重复图案的视图的一部分,使用可拉伸区域。你指定的可拉伸区域可以允许在一个或两个轴方向上拉伸视图。当然,当视图沿着两个轴被拉伸时,视图边缘必须也定义一个可重复的图案,用来避免任何失真。图1-3显示了失真的情况。视图的每个初始像素颜色被复制到了一个更大视图的相应区域里。

Figure 1-3  Stretching the background of abutton

图1-3拉伸按钮的背景


View Programming Guide for iOS——官方文档翻译(2.1)View Architecture Fundamentals_第3张图片

You specify the stretchable area of a view using the contentStretch property.This property accepts a rectangle whose values are normalized to therange0.0to1.0. When stretching the view, the system multiplies these normalized values by the view’s current bounds and scale factor to determine which pixel or pixels need to be stretched. The use of normalized values alleviates the need for you to update thecontentStretchproperty everytime the bounds of your view change.

你可以用contentStretch属性指定视图的可拉伸区域。这个属性接受一个矩形,它的值被规范化到0.0至1.0范围内。当拉伸视图时,系统用这些规范化的值乘以视图当前的边界和缩放因子来决定哪个像素或哪些像素需要被拉伸。标准化值的使用缓解了每次视图边界变化时必须更新contentStretch属性的需求。

The view’s content mode also plays a role in determininghow the view’s stretchable area is used. Stretchable areas are only used whenthe content mode would cause the view’s content to be scaled. This means thatstretchable views are supported only withthe UIViewContentModeScaleToFill, UIViewContentModeScaleAspectFit,  and  UIViewContentModeScaleAspectFill contentmodes. If you specify a content mode that pins the content to an edge or corner(and thus does not actually scale the content), the view ignores thestretchable area.

视图内容模式还决定了如何使用视图的可拉伸区域。可拉伸区域只在内容模式将引起视图的内容被缩放时使用。这意味着可拉伸视图只支持UIViewContentModeScaleToFill,UIViewContentModeScaleAspectFit,和UIViewContentModeScaleAspectFill内容模式。如果你指定了一个把内容固定到一边或一角的内容模式(就是不会拉伸内容),视图将忽视可拉伸区域。

Note: The use of thecontentStretchproperty is recommended over the creation of a stretchableUIImageobject when specifying the background for a view. Stretchableviews are handled entirely in the Core Animation layer, which typically offersbetter performance.

注意:当为视图指定背景时,推荐使用contentStretch属性创建一个可拉伸的UIImage对象。可拉伸视图全部在内核动画层里处理,这样通常提供了更好的性能。

Built-In Animation Support

5.内置动画支持

One of the benefits of having a layer object behind everyview is that you can animate many view-related changes easily. Animations are auseful way to communicate information to the user and should always beconsidered during the design of your application. Many properties of the UIView classare animatable—that is, semiautomatic support exists for animating fromone value to another. To perform an animation for one of these animatableproperties, all you have to do is:

每个视图后面都有一个层对象的好处之一是你可以容易地让许多视图相关的变换动画化。动画是将信息传递给用户的一种很有用的方式,在应用程序设计过程中应该始终被考虑。UIView类的很多属性都是可动画的——就是,半自动化支持动画从一个值到另一个值。为了让这些可动画的属性执行一个动画,你所要做的是:

    1.Tell UIKit that you want to perform an animation.

    告诉UIKit你想要执行一个动画。

    2.Change the value of the property.

    改变属性的值。

Among the properties you can animate on aUIViewobject are the following:

支持动画的UIView对象属性包括:

    ·frame—Usethis to animate position and size changes for the view.

      frame—用它让视图的位置和尺寸变换发生动画。

    ·bounds—Usethis to animate changes to the size of the view.

      bounds—用它让视图的尺寸变化发生动画。

    ·center—Usethis to animate the position of the view.

      center—用它让视图定位发生动画。

    ·transform—Usethis to rotate or scale the view.

      transform—用它旋转或缩放视图

    ·alpha—Usethis to change the transparency of the view.

      alpha—用它改变视图的透明度

    ·backgroundColor—Usethis to change the background color of the view.

      backgroundColor—用它改变视图的背景颜色

    ·contentStretch—Usethis to change how the view’s contents stretch.

      contentStretch—用它改变视图如何拉伸

One place where animations are very important is whentransitioning from one set of views to another. Typically, you use a viewcontroller to manage the animations associated with major changes between partsof your user interface. For example, for interfaces that involve navigatingfrom higher-level to lower-level information, you typically use a navigationcontroller to manage the transitions between the views displaying eachsuccessive level of data. However, you can also create transitions between twosets of views using animations instead of a view controller. You might do so inplaces where the standard view-controller animations do not yield the resultsyou want.

一个动画应用很重要的地方是从一个视图集过渡到另一个视图集。通常,你使用一个视图控制器来管理跟用户界面各部分之间的主要变换有关的动画。例如,对于接口,包括从高级到低级导航信息,您通常使用导航控制器来管理视图显示每个连续的数据之间的转换。然而,你也可以用动画来创建两个视图集之间的过渡,而不用视图控制器。当标准试图控制动画不能得到你想要的效果时,你可能会这样做。

In addition to the animations you create using UIKitclasses, you can also create animations using Core Animation layers. Droppingdown to the layer level gives you much more control over the timing andproperties of your animations.

除了用UIKit类来创建动画,你还可以用内核动画层来创建动画。下降到层级别让你控制更多的动画时机和属性。

For details about how to perform view-based animations,see“Animations.”Formore information about creating animations using Core Animation, see Core Animation Programming Guide and Core Animation Cookbook.

有关如何执行基于视图的动画的更多详情,请看“Animations.”更多关于用内核动画创建动画的信息,请看Core Animation Programming GuideCore Animation Cookbook.

你可能感兴趣的:(View Programming Guide for iOS——官方文档翻译(2.1)View Architecture Fundamentals)