- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
自动布局系统在添加和删除约束时有多宽松?使用不当会导致崩溃、警告,还是什么都不会发生?
特别是,当我执行以下操作时会发生什么情况?
最佳答案
假设我们有以下 UIView
层次结构:
祖父
父亲
目标
儿子
孙子
叔叔
我们定义了 4 个约束(grandFatherConstraint
、fatherConstraint
、targetConstraint
和 sonConstraint
),它们简单地附加了命名 View 与它的正下方。约束的所有者是最近的共同祖先,恰好是约束名称中提到的那个(例如,grandFatherConstraint
归 grandFather
所有)。
例如,grandFatherConstraint
将 grandFather
固定到 father
,使 grandFather
成为此约束的最近共同祖先。同样,targetConstraint
将 target
固定到 son
,target
是最近的共同祖先。
[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.
示例:[目标 addConstraint:targetConstraint]
没有任何反应,它不会第二次添加约束。
示例:[目标 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.
示例:[目标 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.
示例:[父亲addConstraint:targetConstraint]
这是一个没有完整记录的有趣场景。当您运行上面的代码时,它将首先从其当前所有者 (target
) 中删除约束,然后将其重新分配给您指定的新 View (father
)。
因此,上面的代码本质上就变成了:
[target removeConstraint:targetConstraint]
[father addConstraint:targetConstraint]
关于ios - 添加/删除约束时自动布局有多宽容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24792887/
我必须将一个非常大的数据集从一个系统迁移到另一个系统。其中一个“源”列包含一个日期,但实际上是一个没有约束的字符串,而目标系统要求使用 yyyy-mm-dd 格式的日期。 许多(但不是全部)源日期格式
当我拖动可拖动对象时,包含可放置对象的元素不断被触发(因为它也是可放置对象),即使它位于可放置对象后面并且它们彼此堆叠在一起。它的表现就像可放置物体之间有间隙,但其实根本没有间隙。 我做了an exa
我是一名优秀的程序员,十分优秀!