我在NSLayoutConstraint
中遇到了一些问题。通过代码添加和设置NSLayoutConstraint
如果我试图使用setConstant:
方法尝试更改constant
,NSLayoutConstraint给了我一个例外。当我通过代码添加高度约束时,我只有这个问题。
首先,我得到了高度约束,像这样:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"firstAttribute = %d", NSLayoutAttributeWidth];
NSArray *filteredArray = [[self constraints] filteredArrayUsingPredicate:predicate];
return filteredArray[0];
这给了我正确的约束。我有一个NSTextField子类,它可以很好地工作。约束在Interface Builder中设置,我可以设置和修改常量。
现在我有了一个视图,我在运行时添加了不同的子视图。 这些子视图位于自己的NIB中,这意味着我无法固定它们的宽度和高度。 所以我认为只要将视图添加到超级视图中就会添加约束条件。 正在执行viewDidMoveToSuperview
。
// Pin Width & Height
[self addConstraint:[NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0f
constant:self.frame.size.width]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0f
constant:self.frame.size.height]];
约束被添加,我可以用NSLog来证实这一点。
"<NSLayoutConstraint:0x100605cc0 H:[ITControlPanelChildView:0x100616eb0(269)]>",
"<NSLayoutConstraint:0x100614410 V:[ITControlPanelChildView:0x100616eb0(317)]>"
现在,终于,当我尝试使用[constraint setConstant:somethingDifferent];
改变约束我得到以下异常:
Unable to simultaneously satisfy constraints:
(
"<NSLayoutConstraint:0x10192fcb0 V:[ITControlPanelChildView:0x10192e4f0(100)]>",
"<NSAutoresizingMaskLayoutConstraint:0x10053ff10 h=--& v=&-- V:[ITControlPanelChildView:0x10192e4f0(317)]>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x10192fcb0 V:[ITControlPanelChildView:0x10192e4f0(100)]>
这正是我试图改变约束。 任何人都可以向我解释为什么会发生这种情况?
编辑
我刚才读了NSAutoresizingMaskLayoutConstraint
s的自动添加,其中如果设置[self setTranslatesAutoresizingMaskIntoConstraints:NO];
可以禁用。
如果我禁用它,它的作品。
更好的是,如果我可以访问创建的NSAutoresizingMaskLayoutConstraint
。有谁知道这是如何工作的?
认为您在编写我的答案时添加了该编辑功能! Autolayout是否在子视图的xib中打开?你可以显示你用来添加子视图的代码吗? – jrturton
@jrturton是的,自动布局功能已打开。也许你误会了我的意思,这是行得通的。我只是认为如果我可以使用已经为我创建的'NSAutoresizingMaskLayoutConstraint',而不是禁用它们并自己添加约束条件,那将会很好。你明白我的意思吗? – NSAddict
我有,但你不能。我很惊讶他们提出了Autolayout xib顶层定义的视图,这就是为什么我询问代码的原因。 – jrturton