layout issue

来源:互联网 发布:淘宝店铺曼哈顿直通车 编辑:程序博客网 时间:2024/05/21 08:35

http://stackoverflow.com/questions/20609206/setneedslayout-vs-setneedsupdateconstraints-and-layoutifneeded-vs-updateconstra


41 down vote accepted

Your conclusions are right. The basic scheme is:

  • setNeedsUpdateConstraints makes sure a future call to updateConstraintsIfNeeded callsupdateConstraints.
  • setNeedsLayout makes sure a future call to layoutIfNeeded callslayoutSubviews.

When layoutSubviews is called, it also calls updateConstraintsIfNeeded, so calling it manually is rarely needed in my experience. In fact, I have never called it except when debugging autolayouts.

Updating constraints using setNeedsUpdateConstraints is pretty rare too,objc.io–a must read about autolayouts–says:

If something changes later on that invalidates one of your constraints, you should remove the constraint immediately and call setNeedsUpdateConstraints.In fact, that’s the only case where you should have to trigger a constraint update pass.

In addition, in my experience, I have never had to invalidate constraints, and not set thesetNeedsLayout in the next line of the code, because new constraints pretty much are asking for a new layout.

The rules of thumb are:

  • If you manipulated constraints directly, call setNeedsLayout.
  • If you changed some conditions (like offsets or smth) which would change constraints in your overriddenupdateConstraints method (a recommended way to change constraints, btw), callsetNeedsUpdateConstraints, and most of the time, setNeedsLayout after that.
  • If you need any of the actions above to have immediate effect—e.g. when your need to learn new frame height after a layout pass—append it with alayoutIfNeeded.

Also, in your animation code, I believe setNeedsUpdateConstraints is unneeded, constraints are updated before the animation manually, and animation only re-layouts the view based on diff's between old and new ones.


0 0
原创粉丝点击