How to embed WKWebView inside custom UIView properly?

Adelmaer picture Adelmaer · Jan 20, 2017 · Viewed 12.9k times · Source

In my project I have a view controller where i want to show WKWebView embedded inside another UIView titled viewForEmbeddingWebView that i've created in a storyboard (grey on the picture).

grey view titled viewForEmbeddingWebView in my View controller

I've implemented this logic in my ViewController:

import UIKit
import WebKit

class ViewController: UIViewController, WKUIDelegate  {

    var webView: WKWebView!

    @IBOutlet weak var viewForEmbeddingWebView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        webView = WKWebView(frame: viewForEmbeddingWebView.frame, configuration: WKWebViewConfiguration() )
        self.viewForEmbeddingWebView.addSubview(webView)
        self.webView.allowsBackForwardNavigationGestures = true
        let myURL = URL(string: "https://www.apple.com")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)

    }

}

After build and running in Simulator I see the following: after running my code

It shows WKWebView but the bounds look wrong (first: it does not fit the viewForEmbeddingWebView's bounds and second: there is a white gap at the top). I've read that I must use WKWebView on the apple's site https://developer.apple.com/reference/webkit/wkwebview but their example is not my situation, because they only showing how to deal in the situation with loading WKWebView in the whole View of ViewController. But I need it to be embedded into another view because i will also need another ui later around this WKWebView. Before WKWebView there was WebView but since iOS 8 appeared we must use WKWebView. Please help, because i've checked lot of materials but have not find the answer working great with Swift 3 and Xcode 8.

I'm using Xcode 8 and Swift 3 with iOS 10.2.

Answer

Dave Weston picture Dave Weston · Jan 20, 2017

You want to initialize WKWebView like this (Swift 3.0):

webView = WKWebView(frame: viewForEmbeddingWebView.bounds, configuration: WKWebViewConfiguration())
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.viewForEmbeddingWebView.addSubview(webView)