Ios 哪个布局约束优先级相同?
考虑到两个限制:Ios 哪个布局约束优先级相同?,ios,autolayout,nslayoutconstraint,Ios,Autolayout,Nslayoutconstraint,考虑到两个限制: NSLayoutConstraint.activate([ aView.topAnchor.constraint(equalTo: cView.topAnchor) //#1 aView.topAnchor.constraint(greaterThanOrEqualTo: bView.bottomAnchor, constant: 10) //#2 ]) NSLayoutConstraint.activate([ view.height
NSLayoutConstraint.activate([
aView.topAnchor.constraint(equalTo: cView.topAnchor) //#1
aView.topAnchor.constraint(greaterThanOrEqualTo: bView.bottomAnchor, constant: 10) //#2
])
NSLayoutConstraint.activate([
view.heightAnchor.constraint(equalToConstant: 81),
view.heightAnchor.constraint(equalToConstant: 60),
])
让我们假设约束#1中的cView.topAnchor
小于约束#2中的bView.bottomAnchor
这不应该导致自动布局冲突,因为它不能满足两个约束,因为它们具有相同的优先级
奇怪的是,它没有——至少不在日志窗口中,也不在Xcode的调试视图层次结构中
我的方法是将constraint#1的优先级设置为.defaultHigh
,这样自动布局可以在不冲突的情况下打破约束
因此,由于似乎没有冲突,甚至有必要设置优先级吗?基于文档的解释 无法同时满足具有相同优先级的两个(或多个)约束始终会导致冲突。根据: 当系统在运行时检测到不满意的布局时,将执行以下步骤:
经验评估 您可以通过设置两个明确冲突的约束来测试行为:
NSLayoutConstraint.activate([
aView.topAnchor.constraint(equalTo: cView.topAnchor) //#1
aView.topAnchor.constraint(greaterThanOrEqualTo: bView.bottomAnchor, constant: 10) //#2
])
NSLayoutConstraint.activate([
view.heightAnchor.constraint(equalToConstant: 81),
view.heightAnchor.constraint(equalToConstant: 60),
])
这将导致冲突,并将在控制台中报告:
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<NSLayoutConstraint:0x1c0099550 molly.QuestionInboxLinkPreView:0x10791dd40.height == 81 (active)>",
"<NSLayoutConstraint:0x1c008c300 molly.QuestionInboxLinkPreView:0x10791dd40.height == 60 (active)>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x1c0099550 molly.QuestionInboxLinkPreView:0x10791dd40.height == 81 (active)>
我猜原因是,由于不需要已断开的约束
,因此系统不太关心报告它。但它可能会导致一些丑陋的情况——请注意并小心
你的例子 现在考虑你的例子:
NSLayoutConstraint.activate([
aView.topAnchor.constraint(equalTo: cView.topAnchor) //#1
aView.topAnchor.constraint(greaterThanOrEqualTo: bView.bottomAnchor, constant: 10) //#2
])
只是这两个约束不必相互冲突。你说的是a.top=c.top
和a.top>=b.bottom',如果c.top>=b.bottom,就可以满足这个要求。因此,除非存在与
c.top>=b.bottom`冲突的具有相同优先级的其他约束,否则自动布局没有理由识别冲突
此外,如果约束不是.required
,则即使存在冲突,也不会报告冲突。但冲突是c.top
(我的意思是“约束中的cView.topAnchor#1小于约束中的bView.bottomAnchor#2”)。所以你是说一定有冲突,但出于某种原因,它没有显示出来,巧合的是,冲突是通过自动布局以我想要的方式解决的?可能是因为在我的代码中,b.bottom
实际上是视图.safeAreaGuide.bottomAnchor
,因此它在没有日志的情况下创建了一个复杂性。@Manuel我必须假设要么没有真正的冲突,要么你误解了你的约束(当约束复杂时很容易发生),或者他们的优先级已经不是。必需的
,在这种情况下,无论如何都不会报告(阅读更新的答案),因为我可以通过视觉表示来确认布局,所以不太可能误解约束。自动布局可能以特殊方式处理涉及到安全区域布局指南的约束。约束的默认优先级是什么?