Reputation: 409
I would like to insert a UIView into the view hierarchy which covers the entire screen. My approach is to create a UIView instance, add it to the main view , and then add constraints to pin the edges of my new view to the parent view. UIViews themselves do not have an intrinsic content size, but by pinning the edges to the superview, the UIView should have a larger frame.
[self.view setTranslatesAutoresizingMaskIntoConstraints:NO];
UIView *inviteCodeView = [[UIView alloc] initWithFrame:CGRectZero];
inviteCodeView.opaque = NO;
inviteCodeView.alpha = 0.5;
inviteCodeView.backgroundColor = [UIColor colorWithWhite:0.3 alpha:1];
[inviteCodeView setTranslatesAutoresizingMaskIntoConstraints:NO];
inviteCodeView.backgroundColor = [UIColor redColor];
[self.view addSubview:inviteCodeView];
NSDictionary *views = NSDictionaryOfVariableBindings(inviteCodeView);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[inviteCodeView]-0-|" options:0 metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[inviteCodeView]-0-|" options:0 metrics:nil views:views]];
What could be going wrong, or is my understanding of Autolayout incorrect ?
Upvotes: 1
Views: 636
Reputation: 9835
While this doesn't directly answer your question about auto layout, I find doing what you want to do is drastically easier without it. Just set the frame of the view to the frame of the view controller, and set the view's autoresizing mask to flexible height and width and the frame will automatically resize no problem.
UIView *inviteCodeView = [[UIView alloc] initWithFrame:self.view.frame];
inviteCodeView.opaque = NO;
inviteCodeView.alpha = 0.5;
inviteCodeView.backgroundColor = [UIColor colorWithWhite:0.3 alpha:1];
inviteCodeView.autoresizingMask = UIViewAutoresizingFlexibleHeight + UIViewAutoresizingFlexibleWidth;
[self.view addSubview:inviteCodeView];
Also, using your initially provided code, everything works if you remove the first line where you setTranslatesAutoresizingMaskIntoConstraints to NO for the super view:
// [self.view setTranslatesAutoresizingMaskIntoConstraints:NO];
UIView *inviteCodeView = [[UIView alloc] initWithFrame:CGRectZero];
inviteCodeView.opaque = NO;
inviteCodeView.alpha = 0.5;
inviteCodeView.backgroundColor = [UIColor colorWithWhite:0.3 alpha:1];
[inviteCodeView setTranslatesAutoresizingMaskIntoConstraints:NO];
inviteCodeView.backgroundColor = [UIColor redColor];
[self.view addSubview:inviteCodeView];
NSDictionary *views = NSDictionaryOfVariableBindings(inviteCodeView);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[inviteCodeView]-0-|" options:0 metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[inviteCodeView]-0-|" options:0 metrics:nil views:views]];
Upvotes: 2