我在 viewDidLoad 中使用以下代码创建了一个 UIView(其中“secondview”显然是 UIView 的名称):
secondview = [[UIView alloc] initWithFrame:self.view.frame];
[secondview setBackgroundColor: [UIColor yellowColor]];
secondview.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:secondview];
然后在 viewDidAppear 我向这个视图添加了约束:
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:secondview attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeRight
multiplier:1.0f constant:-20.0f];
[self.view addConstraint:constraint];
但是,约束并未应用于视图(至少不是我能看到的)。相反,视图似乎只是从屏幕上消失了。但是,如果约束代码被注释掉,视图将再次加载适当的框架(显然没有应用约束)。将相同的约束应用于 Button 或 ImageView 时,约束会完美应用。这使我认为问题出在创建视图时的“initWithFrame”,因为按钮和 ImageView 实际上都不需要指定它的大小。
你怎么认为?我应该怎么做?