Search code examples
objective-cuiviewcontrollerautolayoutloadview

Adding autolayout constraint programmatically turns uiview to black


I need a view controller without xib. There should be a webview with fully filled to the view. For that I've added the following code to loadView method.

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

}

But this turns the entire view to black. If I coment [view addConstraints:... method calls its showing a green view. What's wrong with my code?


Solution

  • I believe that the problem is that the parent view should not set translatesAutoresizingMaskIntoConstraints to false. The only view that must set that attribute to false is the one you are applying autolayout to, in this case webView. If you set view.translatesAutoresizingMaskIntoConstraints to false then you have to add constraints to view.