这个问题在这里已经有了答案:
uiwebview not resizing after changing orientation to landscape
(2 个回答)
7年前关闭。
我想以编程方式创建一个具有 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];
}
关于ios - 以编程方式创建带有 subview 的 UIViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24568977/