51好读  ›  专栏  ›  Adrenine

iOSSharing #9 | 2019-05-19

Adrenine  · 掘金  ·  · 2019-05-20 08:16

正文

阅读 54

iOSSharing #9 | 2019-05-19

目录

1. setNeedsLayout、layoutIfNeeded与layoutSubviews区别?

2. UIView与CALayer的区别?

3. loadView什么时候被调用?它有什么作用?默认实现是怎么样的?

4. UIViewController的完整生命周期?

5. UIView动画支持的属性有哪些?

1. setNeedsLayout、layoutIfNeeded与layoutSubviews区别?

(1)、setNeedsLayout

用于更新视图以及其子视图布局,不会立即更新,是一个异步方法,需要在主线程调用。该方法将视图以及其子视图标记,在下一个更新周期执行更新操作,不知道具体更新时间。

关于 setNeedsLayout ,官方文档描述如下:

Call this method on your application’s main thread when you want to adjust the layout of a view’s subviews. This method makes a note of the request and returns immediately. Because this method does not force an immediate update, but instead waits for the next update cycle, you can use it to invalidate the layout of multiple views before any of those views are updated. This behavior allows you to consolidate all of your layout updates to one update cycle, which is usually better for performance.

(2)、layoutIfNeeded

用于更新视图以及其子视图布局,立即更新,不会等待更新周期,从根视图开始更新视图子树,若无待更新的布局,直接退出。

关于 layoutIfNeeded ,官方文档描述如下:

Use this method to force the view to update its layout immediately. When using Auto Layout, the layout engine updates the position of views as needed to satisfy changes in constraints. Using the view that receives the message as the root view, this method lays out the view subtree starting at the root. If no layout updates are pending, this method exits without modifying the layout or calling any layout-related callbacks.

(3)、layoutSubviews

一般是在 autoresizing 或者 constraint-based 的情况下重写此方法。常用场景是当视图不是使用frame初始化的时候,我们可以在此方法进行一些精细化布局。如子视图相对于父视图使用约束布局,子视图init时,不具有frame直到约束建立,因为不知道约束建立完成时机,而我们又确实需要frame进行一些计算,为确保计算时拿到的frame不为空,此时,我们可以将计算的过程放于此,并配合 setNeedsLayout 或者 layoutIfNeeded 进行视图刷新。

关于 layoutSubviews ,官方文档描述如下:

Subclasses can override this method as needed to perform more precise layout of their subviews. You should override this method only if the autoresizing and constraint-based behaviors of the subviews do not offer the behavior you want. You can use your implementation to set the frame rectangles of your subviews directly.

You should not call this method directly. If you want to force a layout update, call the setNeedsLayout method instead to do so prior to the next drawing update. If you want to update the layout of your views immediately, call the layoutIfNeeded method.

2. UIView与CALayer的区别?

  • UIView可以响应事件,CALayer不可以响应事件
  • 一个 Layer 的 frame 是由它的 anchorPoint,position,bounds,和 transform 共同决定的,而一个 View 的 frame 只是简单的返回 Layer的 frame
  • UIView主要是对显示内容的管理而 CALayer 主要侧重显示内容的绘制
  • 在做 iOS 动画的时候,修改非 RootLayer的属性(譬如位置、背景色等)会默认产生隐式动画,而修改UIView则不会。

3. loadView什么时候被调用?它有什么作用?默认实现是怎么样的?

1)、什么时候被调用?

每次访问UIViewController的view(比如controller.view、self.view)而且view为nil,loadView方法就会被调用。







请到「今天看啥」查看全文