Trying to create an iOS WKWebView with a size smaller than the screen programmatically

I start with a simple application that simply displays a web view using WKWebView. Everything builds and works fine, except that it is always full-screen mode. Ideally, this does not apply to the iOS status bar at the top. It must be lowered by 20 pixels to be below it. I searched extensively for a solution, but nothing resizes. Nothing is configured in InterfaceBuilder, I do everything programmatically. Using Swift

This is similar to what many applications with WKWebView will do. It should be easy. I probably missed something obvious. Any help is appreciated. Thanks in advance.

This is what I have so far:

import UIKit import WebKit class ViewController: UIViewController, UIGestureRecognizerDelegate , UIWebViewDelegate, WKNavigationDelegate { let url = NSURL(string:"http://stackoverflow.com") var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() webView = WKWebView(frame: CGRect( x: 0, y: 20, width: 380, height: 150 ), configuration: WKWebViewConfiguration() ) self.view = webView self.view.frame = webView.frame let req = NSURLRequest(URL:url!) webView.loadRequest(req) self.webView.allowsBackForwardNavigationGestures = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } 

Thanks a lot Emilio! The configured code works great!

 import UIKit import WebKit class ViewController: UIViewController, UIGestureRecognizerDelegate , UIWebViewDelegate, WKNavigationDelegate { let url = NSURL(string:"http://stackoverflow.com") var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() webView = WKWebView(frame: CGRect( x: 0, y: 20, width: self.view.frame.width, height: self.view.frame.height - 20 ), configuration: WKWebViewConfiguration() ) self.view.addSubview(webView) let req = NSURLRequest(URL:url!) webView.loadRequest(req) self.webView.allowsBackForwardNavigationGestures = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } 
+6
source share
1 answer

Your problem is that UIViewControllers , represented in certain ways, will control the scope of their presentation. If you present it in different ways, for example, as the root controller or the navigation bar, manually setting the glory will have no effect. (These are just a few examples).

If you want to control the view frame, you can add webView as a subtask to your view controller. Then its frame will be changed.

One thing I would like to point out is that calling self.view.frame = webView.frame after calling self.view = webView redundant because both of them are the same object, so you effectively do the following :

 self.view.frame = self.view.frame 
+3
source

All Articles