Search code examples
iosswiftuinavigationcontrollerwkwebview

How to display WKWebView content inside a container view


following code is working but the problem is that this view is in Navigation so the html content goes behind navigation. I want to add another container view inside safe Area and then display html content there. I tried adding a container view and assigning webView to that container view but it didn't work as screen shows black. Can anyone let me know if we can do it and how?

import UIKit import WebKit

class MyViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {

var webView: WKWebView!
var content: String!

override func viewDidLoad() {

    let htmlString = "<html><head><meta name='viewport' content='initial-scale=1.0'/></head><body>" + content
        + "</body></head></html>"

    webView.loadHTMLString(htmlString, baseURL:nil)
}

override func loadView() {
    webView = WKWebView()
    webView.navigationDelegate = self

    webView.uiDelegate = self

    view = webView
}

}


Solution

  • Set the frame of webView

    webView.frame = CGRect(/* set x, y, wifth and height here*/)
    

    or use some autolayout constraints

    webView.translatesAutoresizingMaskIntoConstraints = false
    self.view.addSubview(webView)
    NSLayoutConstraint.activate([
        webView.heightAnchor.constraint(equalToConstant: 300),
        webView.widthAnchor.constraint(equalTo: self.view.widthAnchor),
        webView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
        webView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
    ])