温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

[解析苹果官方文档]之[UIView Class Reference]

发布时间:2020-07-22 19:41:17 来源:网络 阅读:582 作者:mariacarter 栏目:移动开发

The UIView class defines a rectangular area on the screen and the interfaces for managing the content in that area. At runtime, a view object handles the rendering of any content in its area and also handles any interactions with that content. The UIView class itself provides basic behavior for filling its rectangular area with a background color. More sophisticated content can be presented by subclassing UIView and implementing the necessary drawing and event-handling code yourself. The UIKit framework also includes a set of standard subclasses that range from simple buttons to complex tables and can be used as-is. For example, a UILabel object draws a text string and a UIImageView object draws an p_w_picpath.

        UIView类定义了手机屏幕上的一块方形区域,并提供了管理此区域内模块内容的接口。程序运行时,view负责处理本视图区域内所有模块的渲染(render:(v.) process (an outline p_w_picpath) using colour and shading in order to make it appear solid and three-dimensional -> 对轮廓图进行色彩及背景阴影处理,以产生三维立体实物效果),以及用户与这些模块之间的交互。UIView类本身就提供了为此方形区域填充背景色的基础方法。若想展现较为复杂的视图,我们可以创建子类,继承UIView,并按照自己的需求来实现(drawing)绘图以及(event-handling)事件处理的方法。UIKit框架也包含了一系列标准的UIView子类:从简单的UIButton到复杂的UITableView,这些类都可以拿来直接用。比如:UILabel对象 -> 绘制一个字符串;UIImageView对象 -> 绘制一张图片。

Because view objects are the main way your application interacts with the user, they have a number of responsibilities. Here are just a few: 

        view对象是我们的应用与用户交互的主要途径,因此它有如下几项职责:

  • Drawing and animation

    • Views draw content in their rectangular area using technologies such as UIKit, Core Graphics, and OpenGL ES.

    • Some view properties can be animated to new values. 

  • 1). 绘图 + 动画

  • view通过UIKit, Core Graphics, OpenGL ES等技术 绘制方形区域的内容;

  • view的某些属性值的改变可以赋与动画效果。

  • Layout and subview management

    • A view may contain zero or more subviews.

    • Each view defines its own default resizing behavior in relation to its parent view.

    • A view can define the size and position of its subviews as needed.

  • 2). 布局 + 子视图管理

  • view 可包含0或多个子视图;

  • 每个view都定义了在父视图大小发生变化时,重新调整自身大小的默认方法;

  • view可以定义子视图的位置和大小。

  • Event handling

    • 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. 

  • 3). 事件处理

  • UIView继承自UIResponder和NSObject; view本身就是一个responder,因此它能处理触摸点击事件或其他UIResponder类定义的事件;

  • view可以通过addGestureRecognizer方法给视图加载手势识别器,处理常见的手势。

  • Views can embed other views and create sophisticated visual hierarchies. This creates a parent-child relationship between the view being embedded (known as the subview) and the parent view doing the embedding (known as the superview). Normally, a subview’s visible area is not clipped to the bounds of its superview, but in iOS you can use the clipsToBounds property to alter that behavior. A parent view may contain any number of subviews but each subview has only one superview, which is responsible for positioning its subviews appropriately.

  • view可以重重嵌套,产生复杂的视图层级结构(在父视图superview之上嵌入子视图subview)。通常子视图的可视范围不会局限于父视图的边界,但我们可以修改clipToBounds属性值为yes将子视图超出父视图的部分裁剪掉不显示。父视图可以包含多个子视图,但每个子视图只能拥有一个父视图。父视图负责将子视图摆放在合适的位置。

The geometry of a view is defined by its framebounds, and center properties. The frame defines the origin and dimensions of the view in the coordinate system of its superview and is commonly used during layout to adjust the size or position of the view. The center property can be used to adjust the position of the view without changing its size. The bounds defines the internal dimensions of the view as it sees them and is used almost exclusively in custom drawing code. The size portion of the frame and bounds rectangles are coupled together so that changing the size of either rectangle updates the size of both. 

view的几何属性由frame,bounds,center共同决定:

frame:  view在其superview的坐标系中的起始位置frame.origin和尺寸frame.size;常用在布局中调整视图的方位和大小

center: 不改变view的大小,只调整view的位置

bounds: view在自身坐标系中的尺寸;几乎只用于自定义绘图。

frame.size 和 bounds.size是紧密相联的,任意一方改变,另一方均随之改变。

For detailed information about how to use the UIView class, see View Programming Guide for iOS.  


NOTE

In iOS 2.x, the maximum size of a UIView object is 1024 x 1024 points. In iOS 3.0 and later, views are no longer restricted to this maximum size but are still limited by the amount of memory they consume. It is in your best interests to keep view sizes as small as possible. Regardless of which version of iOS is running, you should consider tiling any content that is significantly larger than the dimensions the screen.

       在iOS2.x系统中,视图对象的最大尺寸为1024*1024. 但在iOS3.0及其之后的版本中,视图大小不再局限于这个数字,但仍旧受到所占用内存大小的限制。开发者最好将视图的大小设置得越小越好。不论运行的iOS是哪一版本,都应把比手机屏幕大很多的视图划分(tile)为小模块。


Creating a View    创建视图

To create a view programmatically, you can use code like the following:

  1. CGRect  viewRect = CGRectMake(10, 10, 100, 100);

  2. UIView* myView = [[UIView alloc] initWithFrame:viewRect];

This code creates the view and positions it at the point (10, 10) in its superview’s coordinate system (once it is added to that superview). To add a subview to another view, you use the addSubview: method. In iOS, sibling views may overlap each other without any issues, allowing complex view placement. The addSubview: method places the specified view on top of other siblings. You can specify the relative z-order of a subview by adding it using the insertSubview:aboveSubview: and insertSubview:belowSubview: methods. You can also exchange the position of already added subviews using the exchangeSubviewAtIndex:withSubviewAtIndex: method. 

       以代码方式创建视图:调用initWithFrame:方法;上述代码创建了一个视图,并将其在父视图坐标系统中的起始位置设置为了(10,10)点。我们通过调用addSubview:方法添加子视图。在iOS系统中,sibling views(拥有相同的父视图)可以互相重叠,而且可以进行复杂的位置替换:

addSubview:方法将某一特定视图覆盖于其他同级别的子视图(siblings)之上;

insertSubview:aboveSubview: 和 insertSubview:belowSubview: 方法指定视图在z坐标轴方向上的显示顺序;

exchangeSubviewAtIndex:withSubviewAtIndex: 方法调换两个同级别子视图之间的z坐标轴顺序。

When creating a view, it is important to assign an appropriate value to the autoresizingMask property to ensure the view resizes correctly. View resizing primarily occurs when the orientation of your application’s interface changes but it may happen at other times as well. For example, calling the setNeedsLayout method forces your view to update its layout. 


      此段有关视图的autoresizingMask属性解析见此文:http://mariacarter.blog.51cto.com/4655765/1738641

The View Drawing Cycle 视图的绘制周期

View drawing occurs on an as-needed basis. When a view is first shown, or when all or part of it becomes visible due to layout changes, the system asks the view to draw its contents. For views that contain custom content using UIKit or Core Graphics, the system calls the view’s drawRect: method. Your implementation of this method is responsible for drawing the view’s content into the current graphics context, which is set up by the system automatically prior to calling this method. This creates a static visual representation of your view’s content that can then be displayed on the screen. 

       视图绘制仅在需要的时候才会进行。当某个视图首次显示,或其全部/部分内容由于布局变化从不可见状态变为可见状态时,系统将要求视图进行内容绘制。如果视图包含的是自定义的UIKit或Core Graphics内容,系统会调用视图的drawRect:方法。我们在实现这个方法时,需要将视图的内容绘制到当前的绘图环境中去(这个绘图环境已经在调用drawRect:方法之前由系统自动搭建好了),从而生成视图内容的静态可视界面,随后显示到屏幕上。

When the actual content of your view changes, it is your responsibility to notify the system that your view needs to be redrawn. 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.

       此段有关视图的绘制周期解析见官方文档View Programming Guide for iOS章节。

       略析见此文http://mariacarter.blog.51cto.com/4655765/1738677

NOTE

If you are using OpenGL ES to do your drawing, you should use the GLKView class instead of subclassing UIView. For more information about how to draw using OpenGL ES, see OpenGL ES Programming Guide for iOS.

        如果你使用的是OpenGL ES框架绘图,你应该使用的是GLKView类,而不是继承自UIView类。详见官方文档OpenGL ES Programming Guide for iOS章节。

Animations 动画

Changes to several view properties can be animated—that is, changing the property creates an animation that conveys the change to the user over a short period of time. The UIView class does most of the work of performing the actual animations but you must still indicate which property changes you want to be animated. There are two different ways to initiate animations: 

  • In iOS 4 and later, use the block-based animation methods. (Recommended)

  • Use the begin/commit animation methods.

       view的某些属性值的改变可以做出动画效果-将整个属性的变化过程在较短的时间内展示给用户。虽然UIView类负责大部分的动画操控,但开发者仍需要指定出哪些属性的改变是需要添加动画的。有两种开启动画的方式:

1. 在iOS4及之后的系统中,使用基于代码块block的动画方法(推荐)

2. 使用动画的begin 、commit 方法;

The block-based animation methods (such as animateWithDuration:animations:) greatly simplify the creation of animations. With one method call, you specify the animations to be performed and the options for the animation. However, block-based animations are available only in iOS 4 and later. If your application runs on earlier versions of iOS, you must use the beginAnimations:context: and commitAnimations class methods to mark the beginning and ending of your animations. 

The following properties of the UIView class are animatable:

       基于代码块block的动画方法(例如animateWithDuration:animations:)极大简化了创建动画的步骤,只需在此方法中指定动画内容及动画选项这两个参数。但此方法仅适用于iOS4及以上的系统,对于老版本的系统则需要使用beginAnimations:context:和commitAnimations方法,它们分别标志着动画的开始和结束。UIView的以下属性都是可以加动画效果的:

  • @property frame

  • @property bounds

  • @property center

  • @property transform

  • @property alpha

  • @property backgroundColor

  • @property contentStretch

For more information about how to configure animations, see View Programming Guide for iOS

       有关视图的动画配置,详见官方文档View Programming Guide for iOS章节。

Threading Considerations 涉及多线程的考虑

Manipulations to your application’s user interface must occur on the main thread. Thus, you should always call the methods of the UIView class from code running in the main thread of your application. The only time this may not be strictly necessary is when creating the view object itself but all other manipulations should occur on the main thread. 

       应用中所有的UI操作都必须在主线程中进行。除了创建视图的方法之外,其他所有UIView类中的方法都必须在主线程中被调用。


Subclassing Notes 关于子类的继承  

The UIView class is a key subclassing point for visual content that also requires user interactions. Although there are many good reasons to subclass UIView, it is recommended that you do so only when the basic UIView class or the standard system views do not provide the capabilities that you need. Subclassing requires more work on your part to implement the view and to tune its performance.

For information about ways to avoid subclassing, see Alternatives to Subclassing

       UIView的子类常用于实现视图展示和用户交互的双重效果。建议:如果UIView或系统已实现好的UIView子类可以满足你的需求,那就不要再自定义子类了。关于如何规避对子类的创建,参阅 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:

       创建UIView子类时,仅有为数不多的几个方法应该重写,剩下的很多方法则是根据自己的需要可重写可不重写。UIView具有很高的可配置度,也有很多种其他的途径可以代替实现复杂的视图结构,而不用重写方法。

       以下这几个方法我们可以考虑是否需要重写:

  • 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 - Implement this method 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 override this method and return 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 - Implement this class method 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.

  • addConstraint->  决定视图和子视图的自动布局行为

  • autoresizingMask - Provides automatic layout behavior when the superview’s frame changes. These behaviors can be combined with constraints.

  • autoresizingMask-> 当父视图的frame改变时,决定本视图的自动布局行为;可与上一个方法结合使用

  • 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. 

  • contentMode->  决定视图的bounds变化时,视图内容如何布局(对比frame属性);此属性影响到视图的内容应该如何伸缩以适应本视图,以及视图是需要缓存还是重绘制。

  • contentStretch - Defines portions of the view as being stretchable. This behavior is typically used to implement buttons and other resizable views with sophisticated layout needs where redrawing the view every time would affect performance.

  • contentStretch-> 决定视图的各部分是否可以伸缩。此行为通常用于实现按钮和其他大小可变的视图;这些视图的布局需求较为复杂,可能每次重新绘制视图时都会影响到性能表现。

  • hidden or alpha - Change the transparency of the view as a whole rather than hiding or applying alpha to your view’s rendered content.  

  • hidden / alpha 修改视图整体透明度,不用再隐藏/改变视图所渲染的某一部分内容的透明度

  • backgroundColor - Set the view’s color rather than drawing that color yourself.

  • backgroundColor直接设置视图颜色,省得再自行绘制

  • Subviews - Rather than draw your content using a drawRect: method, embed p_w_picpath and label subviews with the content you want to present. 

  • subviews-> 不用通过drawRect:方法绘制内容,可以考虑直接在p_w_picpath或label上叠放你想展示的子视图;

  • Gesture recognizers - Rather than subclass to intercept and handle touch events yourself, you can use gesture recognizers to send an action message to a target object. 

  • gesture recognizers-> 与其创建子类截获触屏事件,不如用gesture recognizers发送action消息给target对象。

  • 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. 

  • animations-> 最好使用系统内建的动画支持,不要自己实现动画效果。Core Animation框架提供的动画支持高效且易于使用。

  • Image-based backgrounds - For views that display relatively static content, consider using a UIImageViewobject with gesture recognizers instead of subclassing and drawing the p_w_picpath yourself. Alternatively, you can also use a generic UIView object and assign your p_w_picpath as the content of the view’s CALayer object. 

  • 实现视图以图片为背景的静态展示:

  • 1. 直接使用UIImageView对象,搭配gesture recognizers;

  • 2. 使用普通的UIView对象,将图片赋值给view.layer.contents属性。(If you are using the layer to display a static p_w_picpath, you can set this property to the CGImageRef containing the p_w_picpath you want to display. (In OS X 10.6 and later, you can also set the property to an NSImage object.) Assigning a value to this property causes the layer to use your p_w_picpath rather than create a separate backing store. 如果你要用layer对象来显示静态图片,可以将contents属性设置为一个CGImageRef类型的图片;在Mac OS X10.6及之后的版本中,也可以设置为NSImage对象。之后layer将使用你指定的图片,不再创建单独的rendered layer's backing store后端存储)


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.  更多UIView的外观及行为配置,参见UIKit User Interface Catalog

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI