gpt4 book ai didi

ios - UIView 固定到屏幕边缘,但框架保持 0,0

转载 作者:行者123 更新时间:2023-11-29 10:38:49 25 4
gpt4 key购买 nike

我想将一个 UIView 插入到覆盖整个屏幕的 View 层次结构中。我的方法是创建一个 UIView 实例,将其添加到主视图,然后添加约束以将我的新 View 的边缘固定到父 View 。 UIViews 本身没有固有的内容大小,但是通过将边缘固定到 superview,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 的理解不正确?

最佳答案

虽然这不能直接回答您关于自动布局的问题,但我发现没有它,大大您想做的事会更容易。只需将 View 的框架设置为 View Controller 的框架,并将 View 的自动调整大小掩码设置为灵活的高度和宽度,框架将自动调整大小没问题。

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];

此外,使用您最初提供的代码,如果您删除第一行,您将 super View 的 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]];

关于ios - UIView 固定到屏幕边缘,但框架保持 0,0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25575443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com