我想以编程方式创建一个将 UIWebView 作为 subview 的 Controller 。我设法用下面的代码来做到这一点:
VLUpdateViewController.h
@interface VLUpdateViewController : UIViewController
@property (nonatomic, strong) UIWebView* webView;
@end
VLUpdateViewController.m
@implementation VLUpdateViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor blueColor]];
[self.view setTranslatesAutoresizingMaskIntoConstraints:NO];
self.webView = [[UIWebView alloc] initWithFrame:self.view.frame];
[self.webView setBackgroundColor:[UIColor redColor]];
[self.webView setScalesPageToFit:YES];
[self.view addSubview:self.webView];
NSArray* constraints = [[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[webView]-0-|" options:0 metrics:nil views:@{@"webView" : self.webView}] arrayByAddingObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[webView]-0-|" options:0 metrics:nil views:@{@"webView" : self.webView}]];
[self.view addConstraints:constraints];
}
但是,我的问题是当方向改变时 webView 没有正确调整大小。事实上,它根本不会调整大小。它只是在屏幕的中心旋转。
肖像:
横向:
我尝试省略 setTranslatesAutoresizingMaskIntoConstraints:
但当我将方向更改为横向时,我得到了以下结果。
我复制并粘贴了您的代码,并添加了缺失的行:
self.webView.translatesAutoresizingMaskIntoConstraints = NO;
您的 self.view 有 translatesAutoresizingMaskIntoConstraints = NO,但 self.webView 没有。
最终代码:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.view setBackgroundColor:[UIColor blueColor]];
[self.view setTranslatesAutoresizingMaskIntoConstraints:NO];
self.webView = [[UIWebView alloc] initWithFrame:self.view.frame];
[self.webView setBackgroundColor:[UIColor redColor]];
[self.webView setScalesPageToFit:YES];
// ---------------------------------------
// this line is missing
// ---------------------------------------
self.webView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:self.webView];
NSArray* constraints = [[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[webView]-0-|" options:0 metrics:nil views:@{@"webView" : self.webView}] arrayByAddingObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[webView]-0-|" options:0 metrics:nil views:@{@"webView" : self.webView}]];
[self.view addConstraints:constraints];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.google.com/"]];
[self.webView loadRequest:request];
}