什么操作间接使布局无效,因此不需要调用setNeedsLayout()?

huangapple go评论63阅读模式
英文:

What actions indirectly invalidate layout, so setNeedsLayout() call is unnecessary?

问题

我最近开始整理layoutSubviews()setNeedsLayout()layoutIfNeeded()方法。所以,setNeedsLayout()手动将布局标记为无效,因此在下一个更新周期(或在当前周期,如果调用layoutIfNeeded())中,视图将被重新布局和重绘。

但事实证明,如果我使用自动布局(即约束)并更改,例如,某些宽度约束的常数 - 布局会自动间接失效,而无需调用setNeedsLayout()即可更改视图的宽度。

所以,我想知道,还有哪些其他操作会间接使布局失效,这样我就不需要多余地调用setNeedsLayout()

英文:

I've recently started sorting out layoutSubviews(), setNeedsLayout() and layoutIfNeeded() methods.
So, setNeedsLayout() manually sets the layout as invalid, so in the next update cycle (or in the current, if layoutIfNeeded() is called) views will be laid out and redrawed.

But it turned out, that if I use autolayout (i.e. constraints) and change, for example, some width constraint constant – layout automatically and indirectly invalidates and the width of the view changes with no need to call setNeedsLayout().

So, id like to know, what are other actions, that indirectly invalidate layout, so I don't need to redundantly call setNeedsLayout()?

答案1

得分: 0

以下是翻译好的内容:

有多个事件会自动标记一个视图已更改其布局,因此在下一个机会上将调用layoutSubviews(),而不需要开发人员手动调用setNeedsLayout()。

一些自动通知系统视图布局已更改的方式包括:

  • 调整视图大小
  • 添加子视图
  • 用户滚动UIScrollView(layoutSubviews被调用于UIScrollView及其父视图)
  • 用户旋转设备
  • 更新视图的约束

所有这些方式都会通知系统需要重新计算视图位置,并最终自动导致layoutSubviews()被调用。

来源:https://tech.gc.com/demystifying-ios-layout/

英文:

There are multiple events that automatically mark a view as having changed its layout, so that layoutSubviews() will be called at the next opportunity without the developer doing this manually by calling setNeedsLayout().

Some automatic ways to signal to the system that a view’s layout has changed are:

  • Resizing a view
  • Adding a subview
  • User scrolling a UIScrollView (layoutSubviews is called on the UIScrollView and its superview)
  • User rotating their device
  • Updating a view’s constraints

These all communicate to the system that a view’s position needs to be recalculated and will automatically lead to an eventual layoutSubviews() call.

Source: https://tech.gc.com/demystifying-ios-layout/

答案2

得分: 0

需要调用某个视图的 setNeedsLayout,如果你已经子类化了某个视图并且重写了 layoutSubviews 方法。在这个实现中,你可能有一些条件,这些条件会影响方法的行为。所以当条件发生变化时,你需要每次调用 setNeedsLayout
如果你使用自动布局,显然你没有重写 layoutSubviews,也不需要调用 setNeedsLayout

英文:

You need call setNeedsLayout of some view, if you have subclassed some View and override layoutSubviews method. And in that implementation you have some conditions, that affects method behaviour. So you need call setNeedsLayout every time when condition change.
If you use autolayout obviously you haven't override layoutSubviews and don't need call setNeedsLayout

huangapple
  • 本文由 发表于 2023年7月31日 20:41:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76803740.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定