1、[init] does not cause layoutSubviews to be called
2、[addSubview] causes layoutSubviews to be called on the view being added, the view it’s being added to (target view), and all the subviews of the target
3、[view setFrame] intelligently calls layoutSubviews on the view having its frame set only if the size parameter of the frame is different
4、[scrolling] a UIScrollView causes layoutSubviews to be called on the scrollView, and its superview
5、[rotating a device] only calls layoutSubview on the parent view (the responding viewControllers primary view)
6、[Resizing a view] will call layoutSubviews on its superview
也就是说,layoutSubviews 方法会在这些情况下,在这些 UIView 实例上被调用:
1、addSubview 被调用时:target view(一定会),以及被添加的 view(第一次调用会)
2、更改 UIView 的 frame 时:被更改 frame 的 view(frame 与之前不同时)
3、对于 UIScrollView 而言,滚动时:scroll view
4、设备的 orientation 改变时:涉及改变的 UIViewController 的 root view
5、使用 CGAffineTransformScale 改变 view 的 transform 属性时,
6、view 的 superview:被改变的 view
然而,根据我自己的实验,上面的描述并不是很完善的。我的两点补充如下:
1、第一次调用 addSubview 的时候,target view 和被添加到 target view 的 view 的 layoutSubviews 方法会被调用。在已经添加完毕后,若 target view 已经拥有该被添加 view,则只有 target view 的 layoutSubviews 方法会被调用。“and all the subviews of the target” 这句话是错误的。
2、只有 UIView 处于 key window 的 UIView 树中时,该 UIView 的 layoutSubviews 方法才有可能被调用。不在树中的不会被调用。这也是为什么 Stackoverflow 上的讨论中这个答案的第二点会被提出。
小结
使用 layoutSubviews 可以让应用界面的适应能力更强。如果 UIKit 默认提供的自动布局机制 Auto Layout 不能提供给你想要的 UIView 布局行为,你可以自己定制该方法来决定布局行为。
网友评论