以编程方式添加autolayout约束将uiview变为黑色

Joh*_*tty 1 objective-c uiviewcontroller loadview autolayout

我需要一个没有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]];

}
Run Code Online (Sandbox Code Playgroud)

但这会将整个视图变为黑色.如果我执行[view addConstraints:...方法调用它显示绿色视图.我的代码出了什么问题?

Alv*_*aro 5

我认为问题是父视图不应该设置translatesAutoresizingMaskIntoConstraints为false.必须将该属性设置为false的唯一视图是您要应用autolayout的视图,在本例中为webView.如果设置view.translatesAutoresizingMaskIntoConstraints为false,则必须添加约束view.