gpt4 book ai didi

ios - 添加/删除约束时自动布局有多宽容?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:21:56 27 4
gpt4 key购买 nike

自动布局系统在添加和删除约束时有多宽松?使用不当会导致崩溃、警告,还是什么都不会发生?

特别是,当我执行以下操作时会发生什么情况?

  1. 删除不属于目标的约束?
  2. 添加目标已拥有的约束?
  3. 向最近共同祖先之上的 View 添加约束?
  4. 向最近共同祖先之下的 View 添加约束?
  5. 将 View 已经拥有的约束添加到新(有效) View ?

最佳答案

假设我们有以下 UIView 层次结构:

  • 祖父
    • 父亲
      • 目标
        • 儿子
          • 孙子
    • 叔叔

我们定义了 4 个约束(grandFatherConstraintfatherConstrainttargetConstraintsonConstraint),它们简单地附加了命名 View 与它的正下方。约束的所有者是最近的共同祖先,恰好是约束名称中提到的那个(例如,grandFatherConstraintgrandFather 所有)。

例如,grandFatherConstraintgrandFather 固定到 father,使 grandFather 成为此约束的最近共同祖先。同样,targetConstrainttarget 固定到 sontarget 是最近的共同祖先。

1。删除不属于目标的约束?

  • 由后代拥有? (例如 [target removeConstraint:sonConstraint])
  • 由祖先拥有? (例如 [target removeConstraint:grandFatherConstraint])
  • 拥有不同的观点? (例如 [target removeConstraint:uncleConstraint])
  • 一无所有? (例如 [target removeConstraint:nothingConstraint])
  • 查看哪个只是约束的一部分,但仍然不是所有者? (例如 [target removeConstraint:fatherConstraint])

在所有这些情况下,什么都不会发生。约束没有被移除。

根据 removeConstraint:,这是预期的行为文档:

Removing a constraint not held by the view has no effect.

2。添加目标已拥有的约束?

示例:[目标 addConstraint:targetConstraint]

没有任何反应,它不会第二次添加约束。

3。向最近共同祖先之上的 View 添加约束?

示例:[目标 addConstraint:newSonConstraint]

一切看起来都是正确的,但是约束的所有者不会是最近的共同祖先,这可能(也可能不是)您想要的行为。换句话说,它会将约束附加到您指定的 View (target),而不是查找并将其附加到最近的共同祖先 (son)。

这可能是可取的原因是因为约束的所有者在某些情况下很重要。来自addConstraint:文档:

Constraints that are added to a view are said to be held by that view. The coordinate system used when evaluating the constraint is the coordinate system of the view that holds the constraint.

4。向最近共同祖先之下的 View 添加约束?

示例:[目标 addConstraint:newFatherConstraint]

这会导致崩溃。

安装约束后,将记录以下内容:

The view hierarchy is not prepared for the constraint: [...]
When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView _viewHierarchyUnpreparedForConstraint:] to debug.

在释放对主运行循环的控制后,您将遇到崩溃并显示以下消息:

View hierarchy unprepared for constraint.
Constraint: [...]
Container hierarchy: [...]
View not found in container hierarchy: [...]
That view's superview: [...]

根据 addConstraint:,这是预期的行为文档:

The constraint may only reference the view itself or its subviews.

5.将 View 已经拥有的约束添加到新(有效) View ?

示例:[父亲addConstraint:targetConstraint]

这是一个没有完整记录的有趣场景。当您运行上面的代码时,它将首先从其当前所有者 (target) 中删除约束,然后将其重新分配给您指定的新 View (father)。

因此,上面的代码本质上就变成了:

[target removeConstraint:targetConstraint]
[father addConstraint:targetConstraint]

关于ios - 添加/删除约束时自动布局有多宽容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24792887/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com