Objective c 以编程方式创建的NSLayoutconstraint失败

Objective c 以编程方式创建的NSLayoutconstraint失败,objective-c,macos,autolayout,xcode8,nslayoutconstraint,Objective C,Macos,Autolayout,Xcode8,Nslayoutconstraint,我使用的是Xcode 8.3.3,OSX不是iOS 我有一个customView,用作替换其中其他视图的容器。 右侧的深蓝色框表示容器: 容器的约束在IB中设置如下,其中“scrollView”是其左侧的表格滚动视图: 这将启用垂直缩放(允许scrollView垂直缩放),这是所需的行为: 现在,我使用以下代码向容器添加一个子视图: NSStoryboard *storyBoard = [NSStoryboard storyboardWithName:@"Main" bundle:nil]

我使用的是Xcode 8.3.3,OSX不是iOS

我有一个customView,用作替换其中其他视图的容器。 右侧的深蓝色框表示容器:

容器的约束在IB中设置如下,其中“scrollView”是其左侧的表格滚动视图:

这将启用垂直缩放(允许scrollView垂直缩放),这是所需的行为:

现在,我使用以下代码向容器添加一个子视图:

NSStoryboard *storyBoard = [NSStoryboard storyboardWithName:@"Main" bundle:nil];
    _previewViewController = [storyBoard instantiateControllerWithIdentifier:@"showSHPreviewViewController"];

CGRect newFrame = CGRectMake(0, 0,CGRectGetWidth(_previewViewController.view.bounds),CGRectGetHeight(_previewViewController.view.bounds));
_previewViewController.view.frame = newFrame;

[self.previewContainer addSubview:_previewViewController.view];
这与预期的效果一样:

我的问题是,我希望子视图被拉伸,使其适合其容器的整个高度。因此,我必须以编程方式设置NSLayoutConstraints。但我不明白逻辑。。。。无论我尝试什么,都会导致滚动视图和容器都无法垂直缩放的行为

这是我写这篇文章之前的最后一次尝试:

[self.previewContainer addConstraint:[NSLayoutConstraint
    constraintWithItem:_previewViewController.view
    attribute:NSLayoutAttributeTop
    relatedBy:NSLayoutRelationEqual
    toItem:self.previewContainer
    attribute:NSLayoutAttributeTop
    multiplier:1.0
    constant:0]];

[self.previewContainer addConstraint:[NSLayoutConstraint constraintWithItem:_previewViewController.view
    attribute:NSLayoutAttributeLeft
    relatedBy:NSLayoutRelationEqual
    toItem:self.previewContainer
    attribute:NSLayoutAttributeLeft
    multiplier:1.0
    constant:0]];

[self.previewContainer addConstraint:[NSLayoutConstraint constraintWithItem:_previewViewController.view
    attribute:NSLayoutAttributeBottom
    relatedBy:NSLayoutRelationEqual
    toItem:self.previewContainer
    attribute:NSLayoutAttributeBottom
    multiplier:1.0
    constant:0]];

我可以确认添加的子视图的内容设置正确且可调整大小(无“高度锁定”)。

您是否将通过自动布局放置的视图上的
translatesAutoResizengMacintoConstraints
设置为
false
?如果出现这种情况,Xcode控制台将打印布局错误。另一方面,我认为您应该使用UIViewController包含API将视图控制器视图添加为子视图。感谢您的反馈。我根本不设置那个属性。我没有任何UI类,因为我在osx上,而不是在ios上