iosswiftwkwebview

WKWebView's init with frame and config is offset down, iOS swift


I have a UIView called webViewContainer, with proper constraints, and this view has background color red for testing purposes. I need to init WKWebView with frame and configuration. When I do this, the view appears to be offset down (both top and bottom edges are shifted down it seems).

Approach 1:

webView = WKWebView(frame: webViewContainer.frame, configuration: config)
    if let webView = webView {
        webViewContainer.addSubview(webView)
    }

Approach 2:

webView = WKWebView(frame: .zero, configuration: config)
    webView?.frame = webViewContainer.frame
    if let webView = webView {
        webViewContainer = webView
    }

None of the above and conbinations of those seem to work. What am I missing? enter image description here


Solution

  • Since you seem to work with constraints anyway you might wanna add them to your webView as well:

    webView = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())
    if let webView = webView {
       webViewContainer.addSubview(webView)
       webView.translatesAutoresizingMaskIntoConstraints = false
       NSLayoutConstraint.activate([
          webView.leadingAnchor.constraint(equalTo: webViewContainer.leadingAnchor),
          webView.trailingAnchor.constraint(equalTo: webViewContainer.trailingAnchor),
          webView.topAnchor.constraint(equalTo: webViewContainer.topAnchor),
          webView.bottomAnchor.constraint(equalTo: webViewContainer.bottomAnchor)
       ])
    }