我在IB中有以下内容,两个视图都有“使用自动布局”和“调整子视图大小”。
我只是尝试将一个Autolayout View实例添加到容器视图中,使其边缘与容器视图的边缘相交。容器视图使用“自动布局”并且高度相同但宽度是两倍。这是代码:
- (IBAction)addSubviewButton:(id)sender
{
UIView *autolayoutView = [[[NSBundle mainBundle] loadNibNamed:@"AutolayoutView" owner:nil options:nil] objectAtIndex:0];
[self.containerView addSubview:autolayoutView];
[self.containerView addConstraint:
[NSLayoutConstraint constraintWithItem:autolayoutView
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:self.containerView
attribute:NSLayoutAttributeLeading
multiplier:1
constant:0]];
[self.containerView addConstraint:
[NSLayoutConstraint constraintWithItem:autolayoutView
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:self.containerView
attribute:NSLayoutAttributeTrailing
multiplier:1
constant:0]];
[self.containerView addConstraint:
[NSLayoutConstraint constraintWithItem:autolayoutView
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.containerView
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:0.0]];
[self.containerView addConstraint:
[NSLayoutConstraint constraintWithItem:autolayoutView
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.containerView
attribute:NSLayoutAttributeBottom
multiplier:1.0 constant:0.0]];
}
发生错误:
Probably at least one of the constraints in the following list is one you don't want...
(
"<NSIBPrototypingLayoutConstraint:0x8c364d0 'IB auto generated at build time for view with fixed frame' H:[UIView:0x8c356f0(275)]>",
"<NSLayoutConstraint:0x8d43d80 H:|-(0)-[AutolayoutView:0x8d47a30] (Names: '|':UIView:0x8c356f0 )>",
"<NSLayoutConstraint:0x8d09260 AutolayoutView:0x8d47a30.trailing == UIView:0x8c356f0.trailing>",
"<NSAutoresizingMaskLayoutConstraint:0x8d0eca0 h=--& v=--& AutolayoutView:0x8d47a30.midX == + 70>"
)
看起来在将Autolayout View添加为子视图后,会自动在Autolayout View上创建NSAutoresizingMaskLayoutConstraint吗?在didMoveToSuperview中打印Autolayout View的约束时,它尚不存在。怎么解决这个问题?我想尝试在IB中创建对Autolayout View的约束作为占位符在构建时忽略,但IB为Autolayout View禁用了所有自动布局选项。
答案 0 :(得分:33)
删除此约束的最简单方法是将视图的translatesAutoresizingMaskIntoConstraints
设置为Swift中的false
(或Objective-C中的NO
)。你可以在没有任何代码的情况下使用它。您可以在界面构建器中使用键路径(附加屏幕)。