本文为大地瓜原创,欢迎知识共享,转载请注明出处。
虽然你不注明出处我也没什么精力和你计较。
作者微信号:christgreenlaw
UIView对于iOS开发者来说有多重要,不必多言。
本文是对苹果官方UIView Class文档的记录及部分翻译。
大地瓜重温开始了。
不方便翻译的地方会直接保留原文。
UIView
class在屏幕上定义了一个矩形区域,以及在这个区域中管理内容的接口(interface)。
OverView
在运行时(At runtime),一个view对象处理它区域中的内容绘制,也处理和其内容相关的交互。UIView
class自身对带有背景色的矩形区域的(内容)填充提供了基本行为。通过继承UIView
,并实现必要的绘图、事件处理代码,更加复杂的内容可以得到展示。UIKit
框架也包含了一组标准的子类,从简单的按钮到复杂的表格,可以直接使用。例如:一个UILabel
对象绘制一个文本字符串,一个UIImageView
对象绘制一张图片。
由于view对象是应用于用户交互的主要方式,他们就有很多责任。例如:
-
绘制动画
- Views用UIKit、Core Graphics、OpenGL ES这类技术在矩形区域内绘制内容
- 一些view的属性可以animated to new values
-
布局和子view管理
- 一个view可以有0个或多个子view
- 每个view都可以根据父view定义自己的默认resizing behavior
- 一个view可以根据需要调整子view的大小和位置
-
事件处理
A view is a responder and can handle touch events and other events defined by the UIResponder class.
Views can use the addGestureRecognizer: method to install gesture recognizers to handle common gestures.
Views可以嵌套其他的views,建立复杂的可视化层级。这就在被嵌套的view(subview)和进行嵌套的parent view(superview)之间建立了父子关系。一般来说,子view的可视区域不会被superview的边界剪切掉,但是在iOS中你可以通过修改clipToBounds
属性来修改这个行为。
parent view可以包含任意数量的subview,一个subview只能有一个superview,此superview负责适当地摆放subview。
一个view的几何形状位置(geometry)由其frame
、bounds
、center
属性来决定。frame
定义在其superview的坐标系内的origin和dimensions,通常在布局阶段用来调整view的大小和位置。center
属性可用于在不改变大小的情况下调整view的位置。bounds
定义了view的内部dimension,通常在自定义绘图代码中独立使用。frame
和bounds
的size是绑定到一起的,所以改变任一个rectangle的size都会把两个属性的size同时更新。
For detailed information about how to use the UIView class, see View Programming Guide for iOS.
Note
iOS 2.x中,UIView对象最大是1024*1024 points. 在iOS 3.0及以后,view的大小没有要求,但是仍受到内存的限制。最好还是尽可能的让view越小越好。不管是运行的iOS哪个版本,你都应该考虑处理远大于screen尺寸的内容。
Creating A View
To create a view programmatically, you can use code like the following:
CGRect viewRect = CGRectMake(10, 10, 100, 100);
UIView* myView = [[UIView alloc] initWithFrame:viewRect];
这段代码创建了view,将其放置于superview坐标系的(10,10)上(一旦这个view被添加到superview上就立即生效)。要将subview添加到另一个view上,you use the addSubview: method。在iOS中,兄弟(sibling)视图会相互覆盖,不会引发任何错误,这样就可以实现复杂的摆放。你可以使用insertSubview:aboveSubview: and insertSubview:belowSubview: 方法在添加时声明subview的顺序。你也可以使用exchangeSubviewAtIndex:withSubviewAtIndex:方法来交换已经添加的subview的位置顺序。
创建view时,给autoresizingMask属性赋值合适的值极其重要,以此保证view可以正确的resize。
view的resize主要在APP的orientation改变时发生,但是也可能在其他任何时候发生。比如,调用setNeedsLayout 会强制view更新其布局。
The View Drawing Cycle
视图的绘制是按需的。当一个view第一次显示时,或者当其全部或部分由于布局变化而可见时,系统就会要求view绘制其内容。对于包含使用UIKit或Core Graphics自定义内容view来说(For views that contain custom content using UIKit or Core Graphics,)系统调用view的drawRect:方法。此方法的实现负责在当前的graphics上下文中绘制view的内容,which is set up by the system automatically prior to calling this method.这就给接下来展示到屏幕上的内容创建了一个静态可视化的展示。
当你的实际内容变化时,你有责任通知系统你的view需要重绘。You do this by calling your view’s setNeedsDisplay or setNeedsDisplayInRect: method of the view. These methods let the system know that it should update the view during the next drawing cycle. Because it waits until the next drawing cycle to update the view, you can call these methods on multiple views to update them at the same time.
For detailed information about the view drawing cycle and the role your views have in this cycle, see View Programming Guide for iOS.
Animations
某些属性的改变是可以动画的,有两种方式来进行动画:
- iOS 4及以后,可以使用基于block的动画方法(推荐使用)
- 使用begin/commit 动画方法
基于block的动画方法(例如 animateWithDuration:animations:)极大地简化了动画的创建。通过一个方法调用,你可以指定展现的动画以及动画的options。然而,基于block的动画仅仅在iOS 4及以后可以使用,如果你的APP运行在这之前的版本上,you must use the beginAnimations:context: and commitAnimations class methods to mark the beginning and ending of your animations.
可以进行动画的属性如下:
- frame
- bounds
- center
- transform
- alpha
- backGroundColor
For more information about how to configure animations, see View Programming Guide for iOS.
Threading Considerations
APP用户界面的操作必须在主线程发生。因此,你应该永远从APP运行的主线程调用UIView的动画方法。唯一不必这样做的情况就是创建view本身。其他的操作都应该在主线程中执行。
Subclassing Notes
继承的注意事项。
UIView
类对于需要用户交互的可视化内容来说是一个关键的继承点(subclassing point)。尽管有很多理由继承UIView
,还是建议你只有系统提供的标准view不能完成你需要的功能时你再这样做。继承需要你做更多的工作来实现view,调整其性能。
For information about ways to avoid subclassing, see Alternatives to Subclassing.
Methods to Override
When subclassing UIView, there are only a handful of methods you should override and many methods that you might override depending on your needs. Because UIView is a highly configurable class, there are also many ways to implement sophisticated view behaviors without overriding custom methods, which are discussed in the Alternatives to Subclassing section. In the meantime, the following list includes the methods you might consider overriding in your UIView subclasses:
-
Initialization:
initWithFrame: - It is recommended that you implement this method. You can also implement custom initialization methods in addition to, or instead of, this method.
initWithCoder: - Implement this method if you load your view from an Interface Builder nib file and your view requires custom initialization.
layerClass Use this property only if you want your view to use a different Core Animation layer for its backing store. For example, if your view uses tiling to display a large scrollable area, you might want to set the property to the CATiledLayer class.
-
Drawing and printing:
drawRect: - Implement this method if your view draws custom content. If your view does not do any custom drawing, avoid overriding this method.
drawRect:forViewPrintFormatter: - Implement this method only if you want to draw your view’s content differently during printing.
-
Constraints:
requiresConstraintBasedLayout Use this property if your view class requires constraints to work properly.
updateConstraints - Implement this method if your view needs to create custom constraints between your subviews.
alignmentRectForFrame:, frameForAlignmentRect: - Implement these methods to override how your views are aligned to other views.
-
Layout:
sizeThatFits: - Implement this method if you want your view to have a different default size than it normally would during resizing operations. For example, you might use this method to prevent your view from shrinking to the point where subviews cannot be displayed correctly.
layoutSubviews - Implement this method if you need more precise control over the layout of your subviews than either the constraint or autoresizing behaviors provide.
didAddSubview:, willRemoveSubview: - Implement these methods as needed to track the additions and removals of subviews.
willMoveToSuperview:, didMoveToSuperview - Implement these methods as needed to track the movement of the current view in your view hierarchy.
willMoveToWindow:, didMoveToWindow - Implement these methods as needed to track the movement of your view to a different window.
-Event Handling:
touchesBegan:withEvent:, touchesMoved:withEvent:, touchesEnded:withEvent:, touchesCancelled:withEvent: - Implement these methods if you need to handle touch events directly. (For gesture-based input, use gesture recognizers.)
gestureRecognizerShouldBegin:
- Implement this method if your view handles touch events directly and might want to prevent attached gesture recognizers from triggering additional actions.
Alternatives to Subclassing
Many view behaviors can be configured without the need for subclassing. Before you start overriding methods, consider whether modifying the following properties or behaviors would provide the behavior you need.
addConstraint: - Define automatic layout behavior for the view and its subviews.
autoresizingMask - Provides automatic layout behavior when the superview’s frame changes. These behaviors can be combined with constraints.
contentMode - Provides layout behavior for the view’s content, as opposed to the frame
of the view. This property also affects how the content is scaled to fit the view and whether it is cached or redrawn.hidden or alpha - Change the transparency of the view as a whole rather than hiding or applying alpha to your view’s rendered content.
backgroundColor - Set the view’s color rather than drawing that color yourself.
Subviews - Rather than draw your content using a drawRect: method, embed image and label subviews with the content you want to present.
Gesture recognizers - Rather than subclass to intercept and handle touch events yourself, you can use gesture recognizers to send an Target-Action to a target object.
Animations - Use the built-in animation support rather than trying to animate changes yourself. The animation support provided by Core Animation is fast and easy to use.
Image-based backgrounds - For views that display relatively static content, consider using a UIImageView object with gesture recognizers instead of subclassing and drawing the image yourself. Alternatively, you can also use a generic UIView
object and assign your image as the content of the view’s CALayer object.
Animations are another way to make visible changes to a view without requiring you to subclass and implement complex drawing code. Many properties of the UIView
class are animatable, which means changes to those properties can trigger system-generated animations. Starting animations requires as little as one line of code to indicate that any changes that follow should be animated. For more information about animation support for views, see Animations.
For more information about appearance and behavior configuration, see About Views in UIKit User Interface Catalog.