我有一个以编程方式创建 subview 并向其添加一些约束的 View 。由于某种原因,约束被完全忽略了。不会抛出任何错误。约束根本不会生效。 subview 与其父 View 具有相同的框架。我希望它是 400x400 并以其 super View 为中心。我在这里做错了什么?这是我在 super View 中的 initWithFrame:
- (id) initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
instructionsView = [[UIView alloc] initWithFrame:frame];
[self addSubview:instructionsView];
[self bringSubviewToFront:instructionsView];
[self addConstraint:[NSLayoutConstraint constraintWithItem:instructionsView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeCenterX
multiplier:1.
constant:0]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:instructionsView
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeCenterY
multiplier:1.
constant:0]];
[instructionsView addConstraint:[NSLayoutConstraint constraintWithItem:instructionsView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.
constant:400]];
[instructionsView addConstraint:[NSLayoutConstraint constraintWithItem:instructionsView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.
constant:400]];
}
return self;
}
我试过改变
instructionsView = [[UIView alloc] initWithFrame:frame];
到
instructionsView = [[UIView alloc] initWithFrame:CGRectZero];
没有成功。
最佳答案
您需要告诉 View 不要使用基于自动调整大小掩码的布局,而是使用自动布局
instructionsView.translatesAutoresizingMaskIntoConstraints = NO;
此外, View 应该在没有框架的情况下创建,这主要是一种样式,但是像这样创建 View :
instructionsView = [[UIView alloc] init];
关于ios - 为什么我以编程方式创建的 View 会忽略其约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21687722/