Class
UIView
--An object that manages the content for a rectangular area on the screen.
一个对象,用于管理屏幕上矩形内的内容。
Declaration
class UIView : UIResponder //继承于UIResponder
Overview
--Views are the fundamental building blocks of your app's user interface, and the UIView class defines the behaviors that are common to all views. A view object renders content within its bounds rectangle and handles any interactions with that content. The UIView class is a concrete class that you can instantiate and use to display a fixed background color. You can also subclass it to draw more sophisticated content. To display labels, images, buttons, and other interface elements commonly found in apps, use the view subclasses provided by the UIKit framework rather than trying to define your own.
一个view渲染的视图内容和客户交互事件,都是在矩形内进行的。非必要时,建议用api提供的view的子类来满足需求。
--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 UIKit or Core Graphics.
view 使用 UIKit或Core Graphics技术来在矩形内渲染视图内容
-
Some view properties can be animated to new values.
view有一部分属性是可以动画化到另一个值的。
--Layout and subview management
负责子view的布局和管理
-
Views may contain zero or more subviews.
view可以含有0或多个子view
-
Views can adjust the size and position of their subviews.
view可以调整子view的尺寸和大小
-
Use Auto Layout to define the rules for resizing and repositioning your views in response to changes in the view hierarchy.
--Event handling
事件处理
-
A view is a subclass of
UIResponderand can respond to touches and other types of events.
view是UIResponder的子类,可以响应触摸事件和其他事件。
-
Views can install gesture recognizers to handle common gestures.
view可以安装手势识别器,并且可以处理一些公共的手势
--Views can be nested inside other views to create view hierarchies, which offer a convenient way to organize related content. Nesting a view creates a parent-child relationship between the child view being nested (known as the subview) and the parent (known as the superview). A parent view may contain any number of subviews but each subview has only one superview. By default, when a subview’s visible area extends outside of the bounds of its superview, no clipping of the subview's content occurs. Use the clipsToBounds property to change that behavior.
view可以内嵌进view的视图层次中,父view内嵌了子view,一父多子关系。默认,子view的视图内容不会被裁剪,会超出父view的矩形,你可以设置父view的clipsToBounds属性来进行裁剪。
--The geometry of each view is defined by its frame and bounds properties. The frame property defines the origin and dimensions of the view in the coordinate system of its superview. The bounds property defines the internal dimensions of the view as it sees them and is used almost exclusively in custom drawing code. The center property provides a convenient way to reposition a view without changing its frame or bounds properties directly.
view的几何形状由frame and bounds 属性确定。frame属性,定义了在父视图的坐标系中的的原点和维度。bounds属性,定义了view自身的本地坐标系,一般专门用于自定义视图的绘制。center属性,用于重定位view的位置。
--For detailed information about how to use the UIView class, see View Programming Guide for iOS.
更多使用view的信息,看超链接。
Creating a View -- 创建一个View
--Normally, you create views in your storyboards by dragging them from the library to your canvas. You can also create views programmatically. When creating a view, you typically specify its initial size and position relative to its future superview. For example, the following example creates a view and places its top-left corner at the point (10, 10) in the superview's coordinate system (once it is added to that superview).
初始化view时,要指定在父view中的原点和尺寸,下面是示例代码:
let rect = CGRect(x: 10, y: 10, width: 100, height: 100)
let myView = UIView(frame: rect)
--To add a subview to another view, call the addSubview(_:) method on the superview. You may add any number of subviews to a view, and sibling views may overlap each other without any issues in iOS. Each call to the addSubview(_:) method places the new view on top of all other siblings. You can specify the relative z-order of subview by adding it using the insertSubview(_:aboveSubview:) and insertSubview(_:belowSubview:) methods. You can also exchange the position of already added subviews using the exchangeSubview(at:withSubviewAt:) method.
父view的addSubview(_:)方法可以添加子view;每调用一次addSubview(_:)方法,就会压在上一个子view的上面,你可以调用子view的insertSubview(_:aboveSubview:) and insertSubview(_:belowSubview:)方法来确定子view的z轴顺序,也就是插入子view层,汉堡包那样。然后你可以调用父view的exchangeSubview(at:withSubviewAt:)方法来交换子view的几何位置。
After creating a view, create Auto Layout rules to govern how the size and position of the view change in response to changes in the rest of the view hierarchy. For more information, see Auto Layout Guide.
创建自动布局规则,适应父view的几何变化。参考超链接。
The View Drawing Cycle -- View的绘制周期
--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 draw(_:) 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.
view的绘制是需要时才会触发的。当view第一节展示时,或者当view的某部分视图变为可见时,系统就会要求view来绘制它的视图内容。系统通过调用view的draw(_:)方法来绘制view的视图内容,view的视图内容首先会被绘制进“当前的图形上下文”中,而“当前的图形上下文”则是由系统自动设置的,在view绘制图形之前就已经设置好了。
--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 setNeedsDisplay(_:) 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的实际的内容发生改变时,是由你负责通知系统说你要重新绘制视图内容的。你可以调用view的setNeedsDisplay() or setNeedsDisplay(_:)方法来通知系统。通知之后,系统会在下一个绘制周期更新view。
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.
关于用OpenGL ES 技术绘制图形,看超链接。这是另外一种技术,我还没用过。
--For detailed information about the view drawing cycle and the role your views have in this cycle, see View Programming Guide for iOS.
关于view的绘制周期,看超链接。
Animations -- 动画
--Changes to several view properties can be animated—that is, changing the property creates an animation starting at the current value and ending at the new value that you specify. The following properties of the UIView class are animatable:
view的以下几个属性的变化都是可以动画化的。
--To animate your changes, create a UIViewPropertyAnimator object and use its handler block to change the values of your view's properties. The UIViewPropertyAnimator class lets you specify the duration and timing of your animations, but it performs the actual animations. You can pause a property-based animator that is currently running to interrupt the animation and drive it interactively. For more information, see UIViewPropertyAnimator.
你可以创建一个UIViewPropertyAnimator对象,并使用该对象的“处理代码块”来动画化属性的值的变化。你可以暂停基于属性的动画效果,还可以交互式地动画,具体看UIViewPropertyAnimator
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.
你对view的所有操作都应该在主线程中。
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.
能用系统提供的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:
在子类化view时,只用少量方法是必须重写的,但是有大量方法是按需重写的,取决于你。以下的方法的重写应该在你的考虑范围:
Initialization:
初始化:
-
init(frame:)- It is recommended that you implement this method. You can also implement custom initialization methods in addition to, or instead of, this method.
首先建议实现该方法
-
init(coder:)- Implement this method if you load your view from storyboards or nib files and your view requires custom initialization.
用IB编程的话,实现此方法从nib file里加载view
-
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 theCATiledLayerclass.
只用在使用其他类型的底层layer时,才使用该属性。例如可滑动layer
Drawing and printing:
绘制和打印:
-
draw(_:)- Implement this method if your view draws custom content. If your view does not do any custom drawing, avoid overriding this method.
如果你要自定义绘制行为,那就实现这个方法
-
draw(_:for:)- Implement this method only if you want to draw your view’s content differently during printing.
如果你想在打印期间打印不同的绘制的内容,就实现这个方法吧
Layout and Constraints:
布局和约束:
-
requiresConstraintBasedLayoutUse 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.
实现该方法: 更新布局约束
-
alignmentRect(forFrame:),frame(forAlignmentRect:)- Implement these methods to override how your views are aligned to other views.
复写这两个方法:安排两个子view的布局相邻。
-
didAddSubview(_:),willRemoveSubview(_:)- Implement these methods as needed to track the additions and removals of subviews.
实现这两个方法:跟踪子view的添加和删除。
-
willMove(toSuperview:),didMoveToSuperview()- Implement these methods as needed to track the movement of the current view in your view hierarchy.
实现这两个方法:跟踪子view的移动。
Event Handling:
事件处理:
-
gestureRecognizerShouldBegin(_:)- Implement this method if your view handles touch events directly and might want to prevent attached gesture recognizers from triggering additional actions.
如果你想view直接处理触摸事件,并且防止手势触发其他操作,那么就实现该方法吧。这是在手势开始前,view自动调用的方法。
-
touchesBegan(_:with:),touchesMoved(_:with:),touchesEnded(_:with:),touchesCancelled(_:with:)- Implement these methods if you need to handle touch events directly. (For gesture-based input, use gesture recognizers.)
实现这些方法:可以直接处理触摸事件,这些方法都是触摸事件发生的某个时刻自动调用的。
Alternatives to Subclassing
除了子类化view的另一选择
--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.
如果你的需求以下行为可以实现的话,就不需要子类化view了:
-
addConstraint(_:)- Define automatic layout behavior for the view and its subviews.
添加view和子veiw的自动布局约束。可用方法:addConstraint(_:)
-
autoresizingMask- Provides automatic layout behavior when the superview’s frame changes. These behaviors can be combined with constraints.
你可以使用这个autoresizingMask结构体属性的值,来定义自动布局的行为。
-
contentMode- Provides layout behavior for the view’s content, as opposed to theframeof the view. This property also affects how the content is scaled to fit the view and whether it is cached or redrawn.
你可以使用contentMode属性的值,来定义view的缩放行为。
-
isHiddenoralpha- Change the transparency of the view as a whole rather than hiding or applying alpha to your view’s rendered content.
修改view的透明度,你可以使用isHidden or alpha属性
-
backgroundColor- Set the view’s color rather than drawing that color yourself.
改变view的背景颜色
-
Subviews - Rather than draw your content using a
draw(_:)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
UIImageViewobject with gesture recognizers instead of subclassing and drawing the image yourself. Alternatively, you can also use a genericUIViewobject and assign your image as the content of the view’sCALayerobject.
使用基于图片的背景,可以用直接用一个UIImageView对象作为背景,把它复制给view底层的layer的content属性即可。
--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.
view内部提供了很多属性的动画效果,不要着急自己实现动画,先看一下超链接Animations再决定
Topics -- 专题
Creating a View Object -- 创建一个view
--Initializes and returns a newly allocated view object with the specified frame rectangle.
Configuring a View’s Visual Appearance -- 配置view的可见外观
--The view’s background color.
--A Boolean value that determines whether the view is hidden.
--The view’s alpha value.
--A Boolean value that determines whether the view is opaque.
--The first nondefault tint color value in the view’s hierarchy, ascending from and starting with the view itself.
var tintAdjustmentMode: UIView.TintAdjustmentMode
--The first non-default tint adjustment mode value in the view’s hierarchy, ascending from and starting with the view itself.
var clipsToBounds: Bool Bool属性:断定是否裁剪子view内容适应父view的frame
--A Boolean value that determines whether subviews are confined to the bounds of the view.
var clearsContextBeforeDrawing: Bool Bool属性:断定绘制子view时是否先清空ziview的bounds
--A Boolean value that determines whether the view’s bounds should be automatically cleared before drawing.
var mask: UIView? 属性:使用另外一个view的透明度决定该view的视图内容的掩盖程度
--An optional view whose alpha channel is used to mask a view’s content.
class var layerClass: AnyClass get属性:返回创建该view 关联的layer的类,是类,不是实例
--Returns the class used to create the layer for instances of this class.
var layer: CALayer get属性:返回创建该view 关联的layer实例
--The view’s Core Animation layer used for rendering.
Configuring the Event-Related Behavior -- 配置view的与事件相关的行为
var isUserInteractionEnabled: Bool
--A Boolean value that determines whether user events are ignored and removed from the event queue.
var isMultipleTouchEnabled: Bool
--A Boolean value that indicates whether the view receives more than one touch at a time.
var isExclusiveTouch: Bool get属性:断定是否垄断事件的传递,不传给其他view
--A Boolean value that indicates whether the receiver handles touch events exclusively.
Configuring the Bounds and Frame Rectangles -- 配置view的边界和矩形
--The frame rectangle, which describes the view’s location and size in its superview’s coordinate system.
--The bounds rectangle, which describes the view’s location and size in its own coordinate system.
--The center point of the view's frame rectangle.
var transform: CGAffineTransform
--Specifies the transform applied to the view, relative to the center of its bounds.
Managing the View Hierarchy -- 管理view的图层
var superview: UIView? get属性:★接收者的父view
--The receiver’s superview, or nil if it has none.
var subviews: [UIView] get属性:接收者的即时子view数组
--The receiver’s immediate subviews.
--The receiver’s window object, or nil if it has none.
--Adds a view to the end of the receiver’s list of subviews.
func bringSubviewToFront(UIView) 方法:将某子view移到图层的最顶部
--Moves the specified subview so that it appears on top of its siblings.
func sendSubviewToBack(UIView) 方法:将某子view移到图层的最底部
--Moves the specified subview so that it appears behind its siblings.
func removeFromSuperview() ★方法: 将自己从父view的图层中移除
--Unlinks the view from its superview and its window, and removes it from the responder chain.
func insertSubview(UIView, at: Int) 方法:将某子view插入到图层的某索引位置
--Inserts a subview at the specified index.
func insertSubview(UIView, aboveSubview: UIView) 方法:将某子view插入到某子view的顶部
--Inserts a view above another view in the view hierarchy.
func insertSubview(UIView, belowSubview: UIView) 方法:将某子view插入到某子view的底部
--Inserts a view below another view in the view hierarchy.
func exchangeSubview(at: Int, withSubviewAt: Int) 方法:交换两个索引位置的子view
--Exchanges the subviews at the specified indices.
func isDescendant(of: UIView) -> Bool 方法:断定该view是否是某view的子view或说同辈分
--Returns a Boolean value indicating whether the receiver is a subview of a given view or identical to that view.
Observing View-Related Changes -- 观察view相关的变化
func didAddSubview(UIView) 供子类化的方法:当添加子view时,自动调用
--Tells the view that a subview was added.
func willRemoveSubview(UIView) 供子类化的方法:当将要移除子view时,自动调用
--Tells the view that a subview is about to be removed.
func willMove(toSuperview: UIView?) 供子类化的方法:当view成为别人的儿子时,自动调用
--Tells the view that its superview is about to change to the specified superview.
func didMoveToSuperview() 供子类化的方法:当父view已经变更时,自动调用
--Tells the view that its superview changed.
func willMove(toWindow: UIWindow?)
--Tells the view that its window object is about to change.
--Tells the view that its window object changed.
Configuring Content Margins -- 配置内容的边界
Positioning Content Within Layout Margins 文章:关于如何放置view的位置,以至于不会太拥挤
--Position views so that they are not crowded by other content.
var directionalLayoutMargins: NSDirectionalEdgeInsets 属性:视图内容与frame的默认的间距,考虑语言方位在内
--The default spacing to use when laying out content in a view, taking into account the current language direction.
var layoutMargins: UIEdgeInsets 属性:父view和子 view之间默认间距,子view是父view的视图内容啊
--The default spacing to use when laying out content in the view.
var preservesSuperviewLayoutMargins: Bool 属性:断定当前view是否遵循父view的间距设置
--A Boolean value indicating whether the current view also respects the margins of its superview.
func layoutMarginsDidChange() 供子类化的方法:当view的边距发生变化时,自动调用
--Notifies the view that the layout margins changed.
Getting the Safe Area -- 获取安全区域
Positioning Content Relative to the Safe Area 文章:合理放置安全区域中view的视图内容,以至于不会被其他view的视图内容遮住
--Position views so that they are not obstructed by other content.
var safeAreaInsets: UIEdgeInsets
--The insets that you use to determine the safe area for this view.
var safeAreaLayoutGuide: UILayoutGuide
--The layout guide representing the portion of your view that is unobscured by bars and other content.
func safeAreaInsetsDidChange()
--Called when the safe area of the view changes.
var insetsLayoutMarginsFromSafeArea: Bool
--A Boolean value indicating whether the view's layout margins are updated automatically to reflect the safe area.
Managing the View’s Constraints -- 管理view的约束
--Adjust the size and position of the view using Auto Layout constraints.
var constraints: [NSLayoutConstraint]
--The constraints held by the view.
func addConstraint(NSLayoutConstraint)
--Adds a constraint on the layout of the receiving view or its subviews.
func addConstraints([NSLayoutConstraint])
--Adds multiple constraints on the layout of the receiving view or its subviews.
func removeConstraint(NSLayoutConstraint)
--Removes the specified constraint from the view.
func removeConstraints([NSLayoutConstraint])
--Removes the specified constraints from the view.
Creating Constraints Using Layout Anchors -- 创建使用布局锚点的约束
--Attach Auto Layout constraints to one of the view's anchors.
var bottomAnchor: NSLayoutYAxisAnchor
--A layout anchor representing the bottom edge of the view’s frame.
var centerXAnchor: NSLayoutXAxisAnchor
--A layout anchor representing the horizontal center of the view’s frame.
var centerYAnchor: NSLayoutYAxisAnchor
--A layout anchor representing the vertical center of the view’s frame.
var firstBaselineAnchor: NSLayoutYAxisAnchor
--A layout anchor representing the baseline for the topmost line of text in the view.
var heightAnchor: NSLayoutDimension
--A layout anchor representing the height of the view’s frame.
var lastBaselineAnchor: NSLayoutYAxisAnchor
--A layout anchor representing the baseline for the bottommost line of text in the view.
var leadingAnchor: NSLayoutXAxisAnchor
--A layout anchor representing the leading edge of the view’s frame.
var leftAnchor: NSLayoutXAxisAnchor
--A layout anchor representing the left edge of the view’s frame.
var rightAnchor: NSLayoutXAxisAnchor
--A layout anchor representing the right edge of the view’s frame.
var topAnchor: NSLayoutYAxisAnchor
--A layout anchor representing the top edge of the view’s frame.
var trailingAnchor: NSLayoutXAxisAnchor
--A layout anchor representing the trailing edge of the view’s frame.
var widthAnchor: NSLayoutDimension
--A layout anchor representing the width of the view’s frame.
Working with Layout Guides -- 使用布局指引
func addLayoutGuide(UILayoutGuide)
--Adds the specified layout guide to the view.
var layoutGuides: [UILayoutGuide]
--The array of layout guide objects owned by this view.
var layoutMarginsGuide: UILayoutGuide
--A layout guide representing the view’s margins.
var readableContentGuide: UILayoutGuide
--A layout guide representing an area with a readable width within the view.
func removeLayoutGuide(UILayoutGuide)
--Removes the specified layout guide from the view.
Measuring in Auto Layout -- 在自动布局中丈量
func systemLayoutSizeFitting(CGSize) -> CGSize 方法:返回参数尺寸符合自动约束条件之后的最优值尺寸
--Returns the optimal size of the view based on its current constraints.
--Returns the optimal size of the view based on its constraints and the specified fitting priorities.
var intrinsicContentSize: CGSize
--The natural size for the receiving view, considering only properties of the view itself.
func invalidateIntrinsicContentSize()
--Invalidates the view’s intrinsic content size.
func contentCompressionResistancePriority(for: NSLayoutConstraint.Axis) -> UILayoutPriority
--Returns the priority with which a view resists being made smaller than its intrinsic size.
func setContentCompressionResistancePriority(UILayoutPriority, for: NSLayoutConstraint.Axis)
--Sets the priority with which a view resists being made smaller than its intrinsic size.
func contentHuggingPriority(for: NSLayoutConstraint.Axis) -> UILayoutPriority
--Returns the priority with which a view resists being made larger than its intrinsic size.
func setContentHuggingPriority(UILayoutPriority, for: NSLayoutConstraint.Axis)
--Sets the priority with which a view resists being made larger than its intrinsic size.
Aligning Views in Auto Layout -- 在自动布局中校正view
func alignmentRect(forFrame: CGRect) -> CGRect
--Returns the view’s alignment rectangle for a given frame.
func frame(forAlignmentRect: CGRect) -> CGRect
--Returns the view’s frame for a given alignment rectangle.
var alignmentRectInsets: UIEdgeInsets
--The insets from the view’s frame that define its alignment rectangle.
func forBaselineLayout() -> UIView
--Returns a view used to satisfy baseline constraints.
Deprecated var forFirstBaselineLayout: UIView
--Returns a view used to satisfy first baseline constraints.
var forLastBaselineLayout: UIView
--Returns a view used to satisfy last baseline constraints.
Triggering Auto Layout -- 触发自动布局
func needsUpdateConstraints() -> Bool
--A Boolean value that determines whether the view’s constraints need updating.
func setNeedsUpdateConstraints()
--Controls whether the view’s constraints need updating.
--Updates constraints for the view.
func updateConstraintsIfNeeded()
--Updates the constraints for the receiving view and its subviews.
Debugging Auto Layout -- 调试自动布局
See Auto Layout Guide for more details on debugging constraint-based layout.
func constraintsAffectingLayout(for: NSLayoutConstraint.Axis) -> [NSLayoutConstraint]
--Returns the constraints impacting the layout of the view for a given axis.
--A Boolean value that determines whether the constraints impacting the layout of the view incompletely specify the location of the view.
func exerciseAmbiguityInLayout()
--Randomly changes the frame of a view with an ambiguous layout between the different valid values.
Configuring the Resizing Behavior -- 配置自动尺寸调整行为
--Define how a view adjusts its content when its bounds change.
当view的bounds发生改变时,定义view的自动尺寸调整行为。
var contentMode: UIView.ContentMode
--A flag used to determine how a view lays out its content when its bounds change.
--Options to specify how a view adjusts its content when its size changes.
func sizeThatFits(CGSize) -> CGSize
--Asks the view to calculate and return the size that best fits the specified size.
--Resizes and moves the receiver view so it just encloses its subviews.
--A Boolean value that determines whether the receiver automatically resizes its subviews when its bounds change.
var autoresizingMask: UIView.AutoresizingMask
--An integer bit mask that determines how the receiver resizes itself when its superview’s bounds change.
Laying out Subviews -- 布局子view
--Lay out views manually if your app does not use Auto Layout.
func layoutSubviews() --供子类化方法:应用约束规则布局子view,自动调用
--Lays out subviews.
func setNeedsLayout() --方法:无效当前布局,并在下一布局周期刷新布局
--Invalidates the current layout of the receiver and triggers a layout update during the next update cycle.
func layoutIfNeeded() --方法:有挂起的布局,则立马更新布局
--Lays out the subviews immediately, if layout updates are pending.
class var requiresConstraintBasedLayout: Bool
--A Boolean value that indicates whether the receiver depends on the constraint-based layout system.
var translatesAutoresizingMaskIntoConstraints: Bool
--A Boolean value that determines whether the view’s autoresizing mask is translated into Auto Layout constraints.
Adjusting the User Interface -- 调整用户界面
var overrideUserInterfaceStyle: UIUserInterfaceStyle
--The user interface style adopted by the view and all of its subviews.
var semanticContentAttribute: UISemanticContentAttribute
--A semantic description of the view’s contents, used to determine whether the view should be flipped when switching between left-to-right and right-to-left layouts.
var effectiveUserInterfaceLayoutDirection: UIUserInterfaceLayoutDirection
--The user interface layout direction appropriate for arranging the immediate content of the view.
Returns the user interface direction for the given semantic content attribute.
Returns the layout direction implied by the specified semantic content attribute, relative to the specified layout direction.
Adding and Removing Interactions -- 增加和移除客户交互
func addInteraction(UIInteraction)
Adds an interaction to the view.
func removeInteraction(UIInteraction)
Removes an interaction from the view.
var interactions: [UIInteraction]
The array of interactions for the view.
The protocol that an interaction implements to access the view that owns it.
Drawing and Updating the View -- 绘制和更新view
Draws the receiver’s image within the passed-in rectangle.
Marks the receiver’s entire bounds rectangle as needing to be redrawn.
Marks the specified rectangle of the receiver as needing to be redrawn.
var contentScaleFactor: CGFloat
The scale factor applied to the view.
Called by the system when the tintColor property changes.
Formatting Printed View Content -- 格式化用于打印的view的内容
func viewPrintFormatter() -> UIViewPrintFormatter
Returns a print formatter for the receiving view.
func draw(CGRect, for: UIViewPrintFormatter)
Implemented to draw the view’s content for printing.
Managing Gesture Recognizers -- 管理手势识别器
func addGestureRecognizer(UIGestureRecognizer)
Attaches a gesture recognizer to the view.
func removeGestureRecognizer(UIGestureRecognizer)
Detaches a gesture recognizer from the receiving view.
var gestureRecognizers: [UIGestureRecognizer]?
The gesture-recognizer objects currently attached to the view.
func gestureRecognizerShouldBegin(UIGestureRecognizer) -> Bool
Asks the view if the gesture recognizer should be allowed to continue tracking touch events.
Observing Focus -- 观察焦点
A Boolean value that indicates whether the view is currently capable of being focused.
class var inheritedAnimationDuration: TimeInterval
Returns the inherited duration of the current animation.
A Boolean value that indicates whether the item is currently focused.
Using Motion Effects -- 使用运动效应
func addMotionEffect(UIMotionEffect)
Begins applying a motion effect to the view.
var motionEffects: [UIMotionEffect]
The array of motion effects for the view.
func removeMotionEffect(UIMotionEffect)
Stops applying a motion effect to the view.
Preserving and Restoring State -- 保存和恢复view的状态
var restorationIdentifier: String?
The identifier that determines whether the view supports state restoration.
func encodeRestorableState(with: NSCoder)
Encodes state-related information for the view.
func decodeRestorableState(with: NSCoder)
Decodes and restores state-related information for the view.
Capturing a View Snapshot -- 获取view的快照
func snapshotView(afterScreenUpdates: Bool) -> UIView?
Returns a snapshot view based on the contents of the current view.
Returns a snapshot view based on the specified contents of the current view, with stretchable insets.
func drawHierarchy(in: CGRect, afterScreenUpdates: Bool) -> Bool
Renders a snapshot of the complete view hierarchy as visible onscreen into the current context.
Identifying the View at Runtime -- 在运行期识别view
An integer that you can use to identify view objects in your application.
func viewWithTag(Int) -> UIView?
Returns the view whose tag matches the specified value.
Converting Between View Coordinate Systems -- 在view之间的转换坐标系
func convert(CGPoint, to: UIView?) -> CGPoint
Converts a point from the receiver’s coordinate system to that of the specified view.
func convert(CGPoint, from: UIView?) -> CGPoint
Converts a point from the coordinate system of a given view to that of the receiver.
func convert(CGRect, to: UIView?) -> CGRect
Converts a rectangle from the receiver’s coordinate system to that of another view.
func convert(CGRect, from: UIView?) -> CGRect
Converts a rectangle from the coordinate system of another view to that of the receiver.
Hit Testing in a View -- view里的点击测试
func hitTest(CGPoint, with: UIEvent?) -> UIView?
Returns the farthest descendant of the receiver in the view hierarchy (including itself) that contains a specified point.
func point(inside: CGPoint, with: UIEvent?) -> Bool
Returns a Boolean value indicating whether the receiver contains the specified point.
Ending a View Editing Session -- 结束view的编辑对话
Causes the view (or one of its embedded text fields) to resign the first responder status.
Modifying the Accessibility Behavior -- 修改view的可访达行为
var accessibilityIgnoresInvertColors: Bool
A Boolean value indicating whether the view ignores an accessibility request to invert its colors.
Animating Views with Block Objects -- 使用代码块动画化view
Use of these methods is discouraged. Use the UIViewPropertyAnimator class to perform animations instead.
Animate changes to one or more views using the specified duration, delay, options, and completion handler.
Animate changes to one or more views using the specified duration and completion handler.
class func animate(withDuration: TimeInterval, animations: () -> Void)
Animate changes to one or more views using the specified duration.
Creates a transition animation for the specified container view.
Creates a transition animation between the specified views using the given parameters.
Creates an animation block object that can be used to set up keyframe-based animations for the current view.
Specifies the timing and animation values for a single frame of a keyframe animation.
Performs a specified system-provided animation on one or more views, along with optional parallel animations that you define.
Performs a view animation using a timing curve corresponding to the motion of a physical spring.
class func performWithoutAnimation(() -> Void)
Disables a view transition animation.
Animating Views -- 动画化view
Use of these methods is discouraged. Use the UIViewPropertyAnimator class to perform animations instead.
class func beginAnimations(String?, context: UnsafeMutableRawPointer?)
Marks the beginning of a begin/commit animation block.
Deprecatedclass func commitAnimations()
Marks the end of a begin/commit animation block and schedules the animations for execution.
Deprecatedclass func setAnimationStart(Date)
Sets the start time for the current animation block.
Deprecatedclass func setAnimationsEnabled(Bool)
Sets whether animations are enabled.
class func setAnimationDelegate(Any?)
Sets the delegate for any animation messages.
Deprecatedclass func setAnimationWillStart(Selector?)
Sets the message to send to the animation delegate when the animation starts.
Deprecatedclass func setAnimationDidStop(Selector?)
Sets the message to send to the animation delegate when animation stops.
Deprecatedclass func setAnimationDuration(TimeInterval)
Sets the duration (measured in seconds) of the animations in an animation block.
Deprecatedclass func setAnimationDelay(TimeInterval)
Sets the amount of time (in seconds) to wait before animating property changes within an animation block.
Deprecatedclass func setAnimationCurve(UIView.AnimationCurve)
Sets the curve to use when animating property changes within an animation block.
Deprecatedclass func setAnimationRepeatCount(Float)
Sets the number of times animations within an animation block repeat.
Deprecatedclass func setAnimationRepeatAutoreverses(Bool)
Sets whether the animations within an animation block automatically reverse themselves.
Deprecatedclass func setAnimationBeginsFromCurrentState(Bool)
Sets whether the animation should begin playing from the current state.
Deprecatedclass func setAnimationTransition(UIView.AnimationTransition, for: UIView, cache: Bool)
Sets a transition to apply to a view during an animation block.
Deprecatedclass var areAnimationsEnabled: Bool
Returns a Boolean value indicating whether animations are enabled.
Constants -- 一些常量
struct UIView.AnimationOptions
Options for animating views using block objects.
Specifies the supported animation curves.
enum UIView.AnimationTransition
Animation transition options for use in an animation block object.
Option to remove the views from the hierarchy when animation is complete.
struct UIView.KeyframeAnimationOptions
Key frame animation options used with the animateKeyframes(withDuration:delay:options:animations:completion:) method.
Keys that specify a horizontal or vertical layout constraint between objects.
enum UIView.TintAdjustmentMode
The tint adjustment mode for the view.
class let layoutFittingCompressedSize: CGSize
The option to use the smallest possible size.
class let layoutFittingExpandedSize: CGSize
The option to use the largest possible size.
class let noIntrinsicMetric: CGFloat
The absence of an intrinsic metric for a given numeric view property.
struct UIView.AutoresizingMask
Options for automatic view resizing.
enum UISemanticContentAttribute
A semantic description of the view’s contents, used to determine whether the view should be flipped when switching between left-to-right and right-to-left layouts.
Instance Properties -- 实例的属性
var largeContentImage: UIImage?
var largeContentImageInsets: UIEdgeInsets
var largeContentTitle: String?
var playgroundLiveViewRepresentation: PlaygroundLiveViewRepresentation
var scalesLargeContentImage: Bool
var showsLargeContentViewer: Bool
var transform3D: CATransform3D
Type Methods -- 类方法
class func modifyAnimations(withRepeatCount: CGFloat, autoreverses: Bool, animations: () -> Void)

UIView作为iOS应用用户界面的基本构建块,具有多种关键功能,包括绘制内容、处理动画、布局管理、事件处理等。它提供了创建、配置、管理视图的手段,支持Auto Layout进行动态布局,并能响应触摸和其他事件。UIView还支持手势识别、焦点管理、运动效果等功能,允许自定义绘制和动画。开发者可以利用其属性和方法来实现复杂UI交互。
2795

被折叠的 条评论
为什么被折叠?



