1

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?

4

2 回答 2

5

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

于 2015-03-17T16:13:20.047 回答
1

您不需要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应该是全屏的。祝你好运!

于 2015-03-17T15:02:32.610 回答