[Android开发学iOS系列] Auto Layout( 三 )


需要注意的是:

  • 不要remove all constraints然后又add all. 可以把它们分组, 哪些是固定不变的, 那么addView的时候就加上, 然后activate; 对于需要动态变化的部分可以分两组(比如一个根据内容动态决定是否需要显示图片的例子, 可以有两个数组: imageConstraints和noImageConstraints), 单独activate/deactivate这两组约束.
  • 使用isHidden可以提高效率. 比起add/remove Subview来说.
也是WWDC2018/220里提到的, 如何避免Constraint Churn:
  • Avoid removing all constraints
  • Add static constraints once
  • Only change the constraints that need changing
  • Hide views instead of removing them
Size可以选择性地override一些尺寸, 减少text measure计算的过程:
  • Return size if known without text measurement
  • Use UIView.noIntrinsicMetric and constraints.
System Layout Size Fitting Sizeintrinsic content size是view传给engine的.
而这个system layout size fitting size, 是从engine取出来的.
但是它有想不到的性能消耗. (every time you call the method, an engine is created and discarded.)
DebuggingAuto Layout中由约束引起的错误可能会有:
  • 约束自相矛盾(冲突), 不能满足, 无解. (比如一个宽度即等于100又等于200, ???)
  • 约束不足导致有很多可能的解. (Engine会给出一个解, 但可能不是你想要的.)
关于怎么debug可以看: https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/AutolayoutPG/TypesofErrors.html#//apple_ref/doc/uid/TP40010853-CH17-SW1
大体上是根据Log还有一些可能有帮助的view的属性和方法(供debug用).
【[Android开发学iOS系列] Auto Layout】这个视频(https://developer.apple.com/videos/play/wwdc2015/219/)的后半段有讲debug.
这里还有一个小工具网站: https://www.wtfautolayout.com/
SummaryAuto Layout是线性代数的应用实例.
有时候搬砖搬久了是不是应该慢下来欣赏一下数学的美.
References
  • Understanding Auto Layout - Official Doc
  • High Performance Auto Layout - WWDC2018
  • Mysteries of Auto Layout, Part 1 - WWDC 2015
  • Mysteries of Auto Layout, Part 2 - WWDC 2015
  • Auto Layout Basics at codepath
  • The Auto Layout cheat sheet
  • Behind the Scenes with Auto Layout - iOS Conf SG 2019
  • AutoLayout Log分析小工具

推荐阅读