I have an old iOS project using Objective C. When I add a WKWebView to a ViewController
NSURL *url = [NSURL URLWithString:@"https://www.google.com"];
WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
_webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:theConfiguration];
[self.view addSubview:_webView];
self.webView.translatesAutoresizingMaskIntoConstraints = NO;
[NSLayoutConstraint activateConstraints:@[
[self.webView.topAnchor constraintEqualToAnchor:self.view.topAnchor],
[self.webView.leftAnchor constraintEqualToAnchor:self.view.leftAnchor],
[self.webView.rightAnchor constraintEqualToAnchor:self.view.rightAnchor],
[self.webView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor]
]];
[_webView loadRequest:[NSURLRequest requestWithURL:url]];
If I install app via Xcode with iOS 14, webview works fine, but after I disconnect Xcode and open app directly, webview show content with wrong frame. If I build app in iOS 12.5 via Xcode, web view also show content with wrong frame.
If I create new project from Xcode 12.5, and using same code, it works fine.
This is screenshot when open app via Xcode build
https://i.stack.imgur.com/rYb3M.png
And this is screenshot when open app directly:
2
Answers
After spending a few days searching, I finally found the cause of the error. In a UIView Extension file overridden center property
.
Somehow, when loading the webview, it called setCenter which caused the error.
A few observations –
This code uses a mix of
_webView
andself.webView
. For clarity, you should unify the usage for at least this code block.Where exactly are you calling this part?
viewDidLoad()
or After some event? Can you try adding alayoutIfNeeded()
call after you add this?leadingAnchor
&trailingAnchor
instead ofleftAnchor
&rightAnchor
respectively.If nothing helps, I think your view controller’s view storyboard setup isn’t updated to use Autolayout. In that case, you can try this –
Please note that in this case – you MUST REMOVE all the constraints related code.