Samuel Kodytek
Samuel Kodytek

Reputation: 1024

WKWebView add as a subview

From iOS 8.0+, I am supposed to use WKWebView, but in the official Apple documentation, they add it by setting the view as the WKWebView. I need to add it as a subview, for numerous reasons.

  1. I have to add buttons/labels above the WKWebView.
  2. I can add it by adding a UIView to the storyboard and then setting it by code to WKWebView, which looks neater then adding it by code.

My code:

@IBOutlet weak var container: UIView!

private var wkWebView: WKWebView!

override func loadView() {
    let webConfig = WKWebViewConfiguration()
    wkWebView = WKWebView(frame: .zero, configuration: webConfig)
    wkWebView.uiDelegate = self
}

override func viewDidLoad() {
    super.viewDidLoad()

    container = wkWebView

    let url = URL(string: "https://google.com")
    let request = URLRequest(url: url!)
    wkWebView.load(request)
}

I have tried this: WKWebView Add to SubView

I have also tried the container.addSubview method, which crashed with a nil pointer.

Every time I load up the app, there's just a black screen.

Any ideas?

Upvotes: 1

Views: 1825

Answers (1)

glyvox
glyvox

Reputation: 58049

You should just add the instance of WKWebView as a subview to a given view:

view.addSubview(wkWebView)

You can set its frame, add constraints to it etc., just like you would with a UIView.

Upvotes: 2

Related Questions