我需要一个没有xib的视图控制器。应该有一个完全填充到视图的Web视图。为此,我在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:...
方法调用它显示一个绿色视图。我的代码出了什么问题?
我认为问题在于父视图不应该将translatesAutoresizingMaskIntoConstraints
设置为false。唯一必须将该属性设置为false的视图是您正在对其应用自动布局的视图,在本例中为webView。如果将view.translatesAutoresizingMaskIntoConstraints
设置为false,则必须向view
添加约束。
您不需要手动更改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
应该是全屏的。祝你好运