以编程方式创建子视图的UIViewController

hal*_*lei 5 objective-c uiwebview ios

我想创建一个控制器,它以编程方式将UIWebView作为子视图.我设法使用以下代码执行此操作:

VLUpdateViewController.h

@interface VLUpdateViewController : UIViewController

@property (nonatomic, strong) UIWebView* webView;

@end
Run Code Online (Sandbox Code Playgroud)

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];
}
Run Code Online (Sandbox Code Playgroud)

但是,我的问题是,当方向更改时,webView无法正确调整大小.事实上,它根本没有调整大小.它只是在屏幕的一半旋转.

肖像:

在此输入图像描述

景观:

在此输入图像描述

我尝试省略setTranslatesAutoresizingMaskIntoConstraints:但是当我将方向更改为横向时,我得到了以下结果.

在此输入图像描述

Zha*_*ang 1

我复制并粘贴了您的代码,并添加了缺少的行:

self.webView.translatesAutoresizingMaskIntoConstraints = NO;
Run Code Online (Sandbox Code Playgroud)

您的 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];
}
Run Code Online (Sandbox Code Playgroud)