Async-
Async-

Reputation: 3289

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

Upvotes: 0

Views: 2257

Answers (2)

Daniel Marx
Daniel Marx

Reputation: 764

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)
   ])
}

Upvotes: 4

Raja Kishan
Raja Kishan

Reputation: 19044

Here you are setting webViewContainer's frame so the frames have different x and y positions that's why the inner subview set downside.

You should need to use bounds. Bounds return x and y zero so you will get perfect results.

Replace your code with this

webView = WKWebView(frame: webViewContainer.bounds, configuration: config)

Upvotes: 1

Related Questions