您的位置:首页 > 移动开发 > IOS开发

iOS开发 layoutSubviews的作用和调用机制

2017-04-10 10:34 309 查看


一、定义

在UIView里面有一个方法layoutSubviews,这个方法定义如下 

- (void)layoutSubviews; // override point. called by layoutIfNeeded automatically. As of iOS 6.0,
when constraints-based layout is used the base implementation applies the constraints-based layout, otherwise it does nothing.

注:官方解释

Discussion 

The default implementation of this method does nothing on iOS 5.1 and earlier. Otherwise, the default implementation uses any constraints you have set to determine the size and position of any subviews. 

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.

最后一段说,不要直接调用此方法。如果你想强制更新布局,你可以调用setNeedsLayout方法;如果你想立即数显你的views,你需要调用layoutIfNeed方法。


二、layoutSubviews作用

layoutSubviews是对subviews重新布局。比如,我们想更新子视图的位置的时候,可以通过调用layoutSubviews方法,即可以实现对子视图重新布局。 

layoutSubviews默认是不做任何事情的,用到的时候,需要在子类进行重写。


三、layoutSubviews调用机制

①、直接调用setLayoutSubviews。
②、addSubview的时候触发layoutSubviews。
③、当view的frame发生改变的时候触发layoutSubviews。
④、第一次滑动UIScrollView的时候触发layoutSubviews。
⑤、旋转Screen会触发父UIView上的layoutSubviews事件。
⑥、改变一个UIView大小的时候也会触发父UIView上的layoutSubviews事件。

注意: 

init初始化不会触发layoutSubviews,但是使用initWithFrame进行初始化时,当rect的值不为CGRectZero时,也会触发。


四、其他

①、- (void)layoutSubviews; 

这个方法,默认没有做任何事情,需要子类进行重写;
②、- (void)setNeedsLayout; 

标记为需要重新布局,异步调用layoutIfNeeded刷新布局,不立即刷新,但layoutSubviews一定会被调用;
③、- (void)layoutIfNeeded; 

如果,有需要刷新的标记,立即调用layoutSubviews进行布局(如果没有标记,不会调用layoutSubviews)。

如果要立即刷新,要先调用[view setNeedsLayout],把标记设为需要布局,然后马上调用[view layoutIfNeeded],实现布局。在视图第一次显示之前,标记总是“需要刷新”的,可以直接调用[view layoutIfNeeded]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: