我需要一个没有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:...
方法调用它显示绿色视图。我的代码出了什么问题?
答案 0 :(得分:5)
我认为问题是父视图不应该将translatesAutoresizingMaskIntoConstraints
设置为false。必须将该属性设置为false的唯一视图是您要应用autolayout的视图,在本例中为webView。如果您将view.translatesAutoresizingMaskIntoConstraints
设置为false,则必须向view
添加约束。
答案 1 :(得分: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
应全屏显示。祝你好运!