我不知道这是一个错误还是我做错了什么:
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UIWindow *window = [self window];
UIViewController *main = [[UIViewController alloc] init];
UIViewController *vc1 = [[UIViewController alloc] init];
UIViewController *vc2 = [[UIViewController alloc] init];
[main addChildViewController:vc1];
[main addChildViewController:vc2];
UIView *mainView = [main view];
UIView *v1 = [vc1 view];
UIView *v2 = [vc2 view];
[v1 setBackgroundColor:[UIColor redColor]];
[v2 setBackgroundColor:[UIColor blueColor]];
[v1 setTranslatesAutoresizingMaskIntoConstraints:NO];
[v2 setTranslatesAutoresizingMaskIntoConstraints:NO];
[v1 setClipsToBounds:YES];
[v2 setClipsToBounds:YES];
[mainView setBackgroundColor:[UIColor yellowColor]];
[mainView addSubview:v1];
[mainView addSubview:v2];
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:v1
attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual
toItem:mainView attribute:NSLayoutAttributeTop multiplier:1.0
constant:0.0];
[mainView addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:v1
attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual
toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0
constant:240.0];
[mainView addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:v2
attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual
toItem:v1 attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0];
[mainView addConstraint:constraint];
[window setRootViewController:main];
[window setBackgroundColor:[UIColor greenColor]];
[window makeKeyAndVisible];
[main release];
[vc1 release];
[vc2 release];
return YES;
}
当我启动应用程序时, v1
和v2
无处可见。
如果我发表评论:
[v1 setTranslatesAutoresizingMaskIntoConstraints:NO];
[v2 setTranslatesAutoresizingMaskIntoConstraints:NO];
由于自动调整掩码被转换为约束,Cocoa无法满足我的约束。
答案 0 :(得分:3)
您没有任何水平约束,并且缺少v2的高度限制。使用可视格式语言,您需要|-[v1]-|
,|-[v2]-|
和V:[v2]-|
NSArray *constraints;
constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"|-[v1]-|" options:0 metrics:nil views:@{@"v1": v1}];
[mainView addConstraints:constraints];