通过代码添加和设置NSLayoutConstraint

NSA*_*ict 9 macos cocoa objective-c autolayout nslayoutconstraint

我遇到了一些麻烦NSLayoutConstraint.

如果我尝试constant使用该setConstant:方法进行更改,NSLayoutConstraint会给我一个例外.当我通过代码添加高度约束时,我只有这个问题.

首先,我得到高度限制,如下:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"firstAttribute = %d", NSLayoutAttributeWidth];
NSArray *filteredArray = [[self constraints] filteredArrayUsingPredicate:predicate];
return filteredArray[0];
Run Code Online (Sandbox Code Playgroud)

这给了我正确的约束.我有一个NSTextField子类,这是完美的.约束在Interface Builder中设置,我可以设置和更改常量.

现在我有一个视图,我在运行时添加不同的子视图.这些子视图位于自己的NIB中,这意味着我无法固定它们的宽度和高度.所以我认为一旦将视图添加到superview,我就会添加约束.这是在执行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]];
Run Code Online (Sandbox Code Playgroud)

添加了约束,我可以使用NSLog确认.

"<NSLayoutConstraint:0x100605cc0 H:[ITControlPanelChildView:0x100616eb0(269)]>",
"<NSLayoutConstraint:0x100614410 V:[ITControlPanelChildView:0x100616eb0(317)]>"
Run Code Online (Sandbox Code Playgroud)

现在,最后,当我尝试使用[constraint setConstant:somethingDifferent];I 来改变约束时,我得到以下异常:

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)]>
Run Code Online (Sandbox Code Playgroud)

这正是我试图改变的约束.任何人都可以向我解释为什么会这样吗?


编辑

我刚看到NSAutoresizingMaskLayoutConstraints是自动添加的,如果你设置,你可以禁用它[self setTranslatesAutoresizingMaskIntoConstraints:NO];.

如果我禁用它,它的工作原理.

如果我可以访问NSAutoresizingMaskLayoutConstraint创建的内容,那就更好了.有谁知道这是如何工作的?

jrt*_*ton 8

正如您未包含的日志消息的其余部分所示,您已经拥有了您不想要或不需要的自动调整约束.

您可以在添加子视图时删除这些内容.在上面使用的方法中,只需添加以下行:

self.translatesAutoresizingMaskIntoConstraints = NO;
Run Code Online (Sandbox Code Playgroud)

虽然如果你在一个单独的笔尖中创建视图,它的大小是从哪里来的?它是否已经有尺寸限制你可以创建出口?