I want to create a controller which has a UIWebView as a subview programmatically. I manage to do it with the following code:
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];
}
However, my problem is that the webView doesn't resize properly when the orientation changes. In fact, it doesn't resize at all. it just rotates at the cent of the screen.
Portrait:
Landscape:
I tried omitting setTranslatesAutoresizingMaskIntoConstraints:
but I got the following result when i changed the orientation to landscape.
I copy and pasted your code, and added the missing line:
self.webView.translatesAutoresizingMaskIntoConstraints = NO;
You had translatesAutoresizingMaskIntoConstraints = NO for your self.view but not your 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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With