Swift - 约束 - 动态标签宽度

时间:2018-03-10 13:57:12

标签: ios swift autolayout

我在一个"行"中有三个按钮。

A - B --- C

我已经以编程方式添加了这些约束:

A有约束:

leading to superview (value = 16)
width (value = 49)
height (value = 40)
trailing to B (value = 16)
top to top layout guide (value = 16)

B有约束:

width (value = 49)
height (value = 40)
top to top layout guide (value = 16)

C有约束:

trailing to superview (value = 16)
height (value = 40)
top to top layout guide (value = 16)
leading to B (value >= 20)

如果我运行app并抱怨"无法同时满足约束,那么C中的leading to B会导致错误。"

我认为这是由于缺少" C标签的内容(稍后在运行时添加),因此未知宽度。

我已尝试手动添加C:

width (value = 20) 

"错误"仍然存在,但这应该满足导致B> = 20的条件。

However, If I run app, even though the error is printed, the UI looks correct. What is the problem / solution for this?

Unable to simultaneously satisfy constraints.
    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. 
    (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSAutoresizingMaskLayoutConstraint:0x1c4098ab0 h=--& v=--& UIView:topView.width == 0   (active)>",
    "<NSLayoutConstraint:0x1c4092480 H:[UIView:parentParent]-(0)-|   (active, names: '|':UIView:topView )>",
    "<NSLayoutConstraint:0x1c40924d0 UIVIew:topView.leading == UIView:parentParent.leading   (active)>",
    "<NSLayoutConstraint:0x1c0094140 H:|-(0)-[UIView:parent](LTR)   (active, names: '|':UIView:parentParent )>",
    "<NSLayoutConstraint:0x1c00940a0 UIView:parent.right == UIView:parentParent.right   (active)>",
    "<NSLayoutConstraint:0x1c0094000 H:|-(16)-[UIButton:A]   (active, names: '|':UIView:parent )>",
    "<NSLayoutConstraint:0x1c0093f60 UIButton:A.trailing == UIButton:B.leading - 16   (active)>",
    "<NSLayoutConstraint:0x1c0094730 H:[UIButton:B]-(>=20)-[UIButton:C]   (active)>",
    "<NSLayoutConstraint:0x1c0094780 UIButton:C.trailing == UIView:parent.trailing - 16   (active)>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x1c0094730 H:[UIButton:B]-(>=20)-[UIButton:C]   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

其中A,B,C表示按钮,parent是其父视图。整个父视图位于parentParent内,所有视图都在top视图中。

2 个答案:

答案 0 :(得分:2)

您的视图已将自动调整遮罩转换为约束,请尝试将其删除:

button.translatesAutoresizingMaskIntoConstraints = false

答案 1 :(得分:1)

我已经测试了你的约束,但我没有看到错误。

不幸的是,运行时的控制台日志阅读起来并不好玩,如果您使用Xcode&gt; = 7,您可以为约束设置一个标识符,选择它并转到&#34;属性检查器&#34;就像在这张图片中一样:

enter image description here

在此之后,您的日志更具可读性。

如果您遇到问题,可以使用错误的完整日志编辑帖子。

修改

父母视图会出现问题。

在此图片中,您可以看到我的测试(日志中没有错误),我只添加了父级和parentParent的高度限制,您可以检查差异。

enter image description here