关于layoutSubviews的问题

来源:互联网 发布:淘宝美工笨的人难学吗 编辑:程序博客网 时间:2024/05/17 21:58

It’s important to optimize any UIView layoutSubviews method youcreate, as it can be frequently called, and has the potential forcreating recursion (triggering a setNeedsLayout from layoutSubviewscan create a loop that will grossly affect your apps performance).Layout subviews is called once per run loop on any view that hashad setNeedsLayout or setNeedsDisplayWithRect: called on it. So inaddition to any tim you manually call these methods, it can beuseful to know when the UI framework callssetNeedsLayout/setNeedsDisplay as this will triggerlayoutSubviews.

 

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 autoresizemask)
  • View1.1.2 – UIView class, another subview of View1.1(Autoresize mask – flexible width)

I then ran the following tests.  An X means theview 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 beingadded, the view it’s being added to (target view), and all thesubviews of the target view
  • setFrame intelligently calls layoutSubviews on the view havingit’s frame set only if the size parameter of the frame isdifferent
  • scrolling a UIScrollView causes layoutSubviews to be called onthe 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 superviewonly (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 causesthe superview to get -layoutSubviews sent to it, which I foundunexpected. From your table it doesn’t look like you tested thatcase.


 

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

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

1、init初始化不会触发layoutSubviews

2、addSubview会触发layoutSubviews

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

4、滚动一个UIScrollView会触发layoutSubviews

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

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

0 0
原创粉丝点击