I have a UIViewController with a few UIViews (built using Interface Builder) including one that I want to use as a WKWebView. I have been able to create the WKWebView and load it as a subview to one of these UIViews — but when I load the URL I get this strange padding on the top and left. I had the same issue when I use the UIWebView but was able to solve it using
self.automaticallyAdjustsScrollViewInsets = false;
However this does not seem to help at all with the WKWebView that has been loaded dynamically.
I also get the same padding when loading a page from the web so I know its not in my local html.
Edit: I am beginning to wonder whether autolayout in the container UIView is causing this…
Here is the relevant code:
var webView:WKWebView!
@IBOutlet var containerView : UIView?
@IBOutlet weak var webContainer: UIView!
override func loadView() {
super.loadView()
self.webView = WKWebView()
if(self.webView != nil){
self.containerView = self.webView!
self.containerView!.frame = self.webContainer.frame
self.webContainer.addSubview(self.containerView!)
}
}
override func viewDidLoad() {
super.viewDidLoad()
let bundle = NSBundle.mainBundle()
let url = bundle.URLForResource("index", withExtension: "html")
let request = NSURLRequest(URL: url!)
webView.loadRequest(request)
}
Here is what it looks like. The BG color of the UIView container is dark grey — and you'll also note that the html seems to extend beyond the UIView even though I set the frame of the WebView to be the same as the UIView container:
Best Answer
This is because
WKWebView
preserves space for the navigation bar by using an appropriatecontentInset
. However, since your WKWebView is a subview, this adjustment is not necessary anymore.It is important to do this after the
viewDidLoad
method. For example indidFinishedNavigation
in theWKNavigationDelegate