以编程方式添加自动布局约束将 uiview 变为黑色

Adding autolayout constraint programmatically turns uiview to black

我需要一个没有 xib 的视图控制器。应该有一个完全填充视图的 webview。为此,我在 loadView 方法中添加了以下代码。

- (void)loadView {
    CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
    UIView *view = [[UIView alloc] initWithFrame:applicationFrame];

    view.translatesAutoresizingMaskIntoConstraints = NO;
    [view setBackgroundColor:[UIColor greenColor]];
    [self setView:view];
//    //create webview
    self.webview = [[UIWebView alloc] initWithFrame:CGRectZero];
    self.webview.translatesAutoresizingMaskIntoConstraints = NO;
    [view addSubview:self.webview];
    [self.webview setBackgroundColor:[UIColor orangeColor]];
    [self.webview setDelegate:self];

    NSDictionary *viewBindings = NSDictionaryOfVariableBindings(view,_webview);
//    //add constraints
    [view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_webview]|" options:0 metrics:nil views:viewBindings]];
    [view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_webview]|" options:0 metrics:nil views:viewBindings]];

}

但这会将整个视图变成黑色。如果我评论 [view addConstraints:... 方法调用它显示绿色视图。我的代码有什么问题?

您不需要手动更改 UIViewController 的根视图,也许这就是它不起作用的原因。

我的建议是尝试一下:

- (void) viewDidLoad {
    [super viewDidLoad];

    self.webview = [[UIWebView alloc] init];
    self.webview.translatesAutoresizingMaskIntoConstraints = NO;
    [view addSubview:self.webview];
    [self.webview setBackgroundColor:[UIColor orangeColor]];
    [self.webview setDelegate:self];

    NSDictionary *viewBindings = NSDictionaryOfVariableBindings(view,_webview);
    [view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[_webview]-0-|" options:0 metrics:nil views:viewBindings]];
    [view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[_webview]-0-|" options:0 metrics:nil views:viewBindings]];
    // put a breakpoint after this line to see the frame of your UIWebView. 
    // It should be the same as the view
    [self.view layoutIfNeeded];
}

这应该可以,您的 UIWebView 应该是全屏的。祝你好运!

我认为问题在于父视图不应将 translatesAutoresizingMaskIntoConstraints 设置为 false。唯一必须将该属性设置为 false 的视图是您要对其应用自动布局的视图,在本例中为 webView。如果将 view.translatesAutoresizingMaskIntoConstraints 设置为 false,则必须向 view.

添加约束