溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

[解析蘋果官方文檔]之[UIView Class Reference]

發(fā)布時間:2020-07-22 19:41:17 來源:網絡 閱讀:598 作者:mariacarter 欄目:移動開發(fā)

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類定義了手機屏幕上的一塊方形區(qū)域,并提供了管理此區(qū)域內模塊內容的接口。程序運行時,view負責處理本視圖區(qū)域內所有模塊的渲染(render:(v.) process (an outline p_w_picpath) using colour and shading in order to make it appear solid and three-dimensional -> 對輪廓圖進行色彩及背景陰影處理,以產生三維立體實物效果),以及用戶與這些模塊之間的交互。UIView類本身就提供了為此方形區(qū)域填充背景色的基礎方法。若想展現(xiàn)較為復雜的視圖,我們可以創(chuàng)建子類,繼承UIView,并按照自己的需求來實現(xiàn)(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等技術 繪制方形區(qū)域的內容;

  • 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都定義了在父視圖大小發(fā)生變化時,重新調整自身大小的默認方法;

  • 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是緊密相聯(lián)的,任意一方改變,另一方均隨之改變。

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系統(tǒng)中,視圖對象的最大尺寸為1024*1024. 但在iOS3.0及其之后的版本中,視圖大小不再局限于這個數(shù)字,但仍舊受到所占用內存大小的限制。開發(fā)者最好將視圖的大小設置得越小越好。不論運行的iOS是哪一版本,都應把比手機屏幕大很多的視圖劃分(tile)為小模塊。


Creating a View    創(chuàng)建視圖

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. 

       以代碼方式創(chuàng)建視圖:調用initWithFrame:方法;上述代碼創(chuàng)建了一個視圖,并將其在父視圖坐標系統(tǒng)中的起始位置設置為了(10,10)點。我們通過調用addSubview:方法添加子視圖。在iOS系統(tǒng)中,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. 

       視圖繪制僅在需要的時候才會進行。當某個視圖首次顯示,或其全部/部分內容由于布局變化從不可見狀態(tài)變?yōu)榭梢姞顟B(tài)時,系統(tǒng)將要求視圖進行內容繪制。如果視圖包含的是自定義的UIKit或Core Graphics內容,系統(tǒng)會調用視圖的drawRect:方法。我們在實現(xiàn)這個方法時,需要將視圖的內容繪制到當前的繪圖環(huán)境中去(這個繪圖環(huán)境已經在調用drawRect:方法之前由系統(tǒng)自動搭建好了),從而生成視圖內容的靜態(tài)可視界面,隨后顯示到屏幕上。

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章節(jié)。

       略析見此文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章節(jié)。

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類負責大部分的動畫操控,但開發(fā)者仍需要指定出哪些屬性的改變是需要添加動畫的。有兩種開啟動畫的方式:

1. 在iOS4及之后的系統(tǒng)中,使用基于代碼塊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:)極大簡化了創(chuàng)建動畫的步驟,只需在此方法中指定動畫內容及動畫選項這兩個參數(shù)。但此方法僅適用于iOS4及以上的系統(tǒng),對于老版本的系統(tǒng)則需要使用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章節(jié)。

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操作都必須在主線程中進行。除了創(chuàng)建視圖的方法之外,其他所有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的子類常用于實現(xiàn)視圖展示和用戶交互的雙重效果。建議:如果UIView或系統(tǒng)已實現(xiàn)好的UIView子類可以滿足你的需求,那就不要再自定義子類了。關于如何規(guī)避對子類的創(chuàng)建,參閱 Alternatives to Subclassing 章節(jié)。

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:

       創(chuàng)建UIView子類時,僅有為數(shù)不多的幾個方法應該重寫,剩下的很多方法則是根據自己的需要可重寫可不重寫。UIView具有很高的可配置度,也有很多種其他的途徑可以代替實現(xiàn)復雜的視圖結構,而不用重寫方法。

       以下這幾個方法我們可以考慮是否需要重寫:

  • 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 不用創(chuàng)建子類,還可以怎么做?

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.

許多視圖行為的實現(xiàn)都不用通過創(chuàng)建子類的方式,在重寫部分方法之前,思考一下是否通過設置以下的屬性就可以達到你想要的效果:

  • 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-> 決定視圖的各部分是否可以伸縮。此行為通常用于實現(xiàn)按鈕和其他大小可變的視圖;這些視圖的布局需求較為復雜,可能每次重新繪制視圖時都會影響到性能表現(xiàn)。

  • 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-> 與其創(chuàng)建子類截獲觸屏事件,不如用gesture recognizers發(fā)送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-> 最好使用系統(tǒng)內建的動畫支持,不要自己實現(xiàn)動畫效果。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. 

  • 實現(xiàn)視圖以圖片為背景的靜態(tài)展示:

  • 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對象來顯示靜態(tài)圖片,可以將contents屬性設置為一個CGImageRef類型的圖片;在Mac OS X10.6及之后的版本中,也可以設置為NSImage對象。之后layer將使用你指定的圖片,不再創(chuàng)建單獨的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問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI