我想将UIView插入到覆盖整个屏幕的视图层次结构中。我的方法是创建一个UIView实例,将其添加到主视图,然后添加约束以将我的新视图的边缘固定到父视图。 UIViews本身没有固有的内容大小,但是通过将边缘固定到超视图,UIView应该有一个更大的帧。
[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]];
可能出现什么问题,或者我对Autolayout的理解不正确?
答案 0 :(得分:2)
虽然这并没有直接回答你关于自动布局的问题,但我觉得如果没有它,你想要做的就是彻底。只需将视图的框架设置为视图控制器的框架,并将视图的自动调整遮罩设置为灵活的高度和宽度,框架将自动调整大小没有问题。
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];
此外,使用您最初提供的代码,如果您删除第一个行,其中setTranslatesAutoresizingMaskIntoConstraints为超级视图的NO,则一切正常:
// [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]];