Eddie Eddie - 5 months ago 85
Swift Question

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

Im starting with a simple app that just shows a web view using WKWebView.
Everything builds, and works okay, except that it is always fullscreen. Ideally it would not extend under the iOS status bar at the top. It needs to be lowered by 20px to be below it. I have searched extensively for a solution but nothing changes the size. Nothing is setup in InterfaceBuilder, I'm doing everything programmatically. Using Swift.

This seems like something basic that many apps with a WKWebView would do. It should be simple. I'm probably missing 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./Users/owner/Desktop/xCodeApps/Navi/Navi/AppDelegate.swift
}
}

Answer

Your problem is that UIViewControllers presented in certain ways will manage the frame of their view. If you present it modally, as the root controller, or in a navigation bar, for example, setting the fame manually won't have an effect. (Those are only a few examples).

If you want to manage the frame of the view, you can add the webView as a subview to your view controller's view. Modifying it's frame will work then.

One thing I'd like to point out is that calling self.view.frame = webView.frame after calling self.view = webView is redundant, because they are both the same object, so what you are effectively doing is:

self.view.frame = self.view.frame
Comments