您的位置:首页 > 其它

layoutSubviews何时被调用

2013-11-07 14:05 288 查看
layoutSubviews何时调用的问题,这个方法是当你需要在调整subview的大小的时候需要重写(我这个翻译不严谨,以下是原文:You should override this method only if the autoresizing behaviors of the subviews do not offer the behavior you want.),但有时候经常指望它被调用的时候没被调用,不希望它被调用的时候被调用了,搞的很上火。根据国外社区一个人帖子,做了总结性翻译。

layoutSubviews在以下情况下会被调用:

1、init初始化不会触发layoutSubviews

2、addSubview会触发layoutSubviews

3、设置view的Frame会触发layoutSubviews,当然前提是frame的值设置前后发生了变化

4、滚动一个UIScrollView会触发layoutSubviews

5、旋转Screen会触发父UIView上的layoutSubviews事件

6、改变一个UIView大小的时候也会触发父UIView上的layoutSubviews事件

UIView的layoutSubviews什么时候被调用

It’s important to optimize any UIView layoutSubviews method you create, as it can be frequently called, and has the potential for creating recursion (triggering a setNeedsLayout from layoutSubviews can create a loop that will grossly affect your apps performance). Layout subviews is called once per run loop on any view that has had setNeedsLayout or setNeedsDisplayWithRect: called on it. So in addition to any tim you manually call these methods, it can be useful to know when the UI framework calls setNeedsLayout/setNeedsDisplay as this will trigger layoutSubviews.

For this purpose, I will define a few view relationships:

View1 – UIView class, root view for examples

View1.1 – UIScrollView class, subview of View1

View1.1.1 – UIView class, subview of View1.1 (No autoresize mask)

View1.1.2 – UIView class, another subview of View1.1 (Autoresize mask – flexible width)

I then ran the following tests. An X means the view was layed out



From this I surmise the following:

init does not cause layoutSubviews to be called (duh)

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 view

setFrame intelligently calls layoutSubviews on the view having it’s frame set only if the size parameter of the frame is different

scrolling a UIScrollView causes layoutSubviews to be called on the scrollView, and it’s superview

rotating a device only calls layoutSubview on the parent view (the responding viewControllers primary view)

removeFromSuperview – layoutSubviews is called on superview only (not show in table)

Hopefully this is helpful information for you as well.

1 comment:

I find that resizing (not moving, only resizing) any subview causes the superview to get -layoutSubviews sent to it, which I found unexpected. From your table it doesn’t look like you tested that case.

转自 http://blog.csdn.net/frankwun/article/details/7564588
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: