我总是在代码中创建我的视图,因此从未使用过自动布局(直到现在)。不使用nib的原因是因为我更喜欢代码,并且通过GitHub等进行维护更简单,但足够了。
我有一种情况,我在屏幕上放置了三个标签,彼此相邻。像这样:|Label1| - some space - |Label2| - some space - |Label3|
。有些空间可以说是15分。现在我想要完成的是,当我更改标签的文本时,我会在它们上面调用sizeToFit
,并希望它们相互间隔10磅。我知道我可以通过一些数学来解决这个问题,但这并不困难,但我认为自动布局会更容易,更容易理解,我将在此过程中学习一些新东西。所以我做的是:
然后我尝试在它们之间设置约束:
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"[label1]-15-[label2]-15-[label3]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(label1, label2, label3)];
[self addConstraints:constraints]; //Im subclassing an UIView that's why self
但是我收到一个错误说:
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)
(
"<NSLayoutConstraint:0x14c14110 H:[UILabel:0x14c12ab0]-(15)-[UILabel:0x14c12f80]>",
"<NSAutoresizingMaskLayoutConstraint:0x14c08b00 h=--& v=--& UILabel:0x14c12ab0.midX == + 195>",
"<NSAutoresizingMaskLayoutConstraint:0x14c0dd90 h=--& v=--& H:[UILabel:0x14c12ab0(40)]>",
"<NSAutoresizingMaskLayoutConstraint:0x14c1c170 h=--& v=--& UILabel:0x14c12f80.midX == + 237.5>",
"<NSAutoresizingMaskLayoutConstraint:0x14c12f00 h=--& v=--& H:[UILabel:0x14c12f80(40)]>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x14c14110 H:[UILabel:0x14c12ab0]-(15)-[UILabel:0x14c12f80]>
即使我尝试在标签2和3上这样做,也会发生同样的事情。我不完全理解NSLog的说法。
非常感谢任何帮助。此外,如果你有什么好的链接去哪里解码&#34;那些h=--& v=--& UILabel:0x14c12f80.midX == + 237.5
事情会很棒。
答案 0 :(得分:2)
h=
和v=
是自动调整掩码被转换为约束的签名。您是否忘了在其中一个观点上设置translatesAutoResizingMasksToConstraints = NO
?