gduh
gduh

Reputation: 1182

WKWebView does not appear in a custom UIView

I have a custom UIView with its xib. The xib is empty except the content view.

In the corresponding class I load the xib, then I try to create a WKWebView like this :

@IBOutlet var contentView: UIView!

...

Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)
addSubview(contentView)
contentView.frame = self.bounds

let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: self.frame, configuration: webConfiguration)
webView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(webView)

webView.backgroundColor = UIColor.orange    // Just to check visually 

And in my UIViewController :

let v = CustomView.init(frame: frame)
self.view.addSubview(v)

When I run my project, when the view controller appears I can see the Web view with its orange background but it disappears immediately, what is wrong in my code ?

Upvotes: 4

Views: 2569

Answers (3)

gduh
gduh

Reputation: 1182

I found a solution about my issue.

Initially I used contentView.addSubview(webView). contentView is at the first level of my xib, created automatically when I create a new xib.

To solve my problem, I created an UIView as a subview of the contentView directly in Interface Builder. Then, in y code I added the web view as a subview of this new view and not from the contentView. And now it's ok.

So, in brief

  • the situation before : xib's contentView --> webView
  • The situation now : xib's contentView --> UIView --> webView

Upvotes: 0

matt
matt

Reputation: 536028

Delete this line:

webView.translatesAutoresizingMaskIntoConstraints = false

That line means, Use my constraints. You have no constraints so when layout happens the web view ends up with no size or position.

Upvotes: 0

Ashok
Ashok

Reputation: 6244

Note, webView.backgroundColor doesn't work as expected. Try using load url function or call loadHTMLString to verify.

Just to ensure its not a layout issue, use "Debug View Hierarchy" (click double rectangle icon in Xcode when Debug run the app) to check the bounds/frame of your subviews. If you see issues there, then you need to add proper layout constraints.

If so, you may also use below utility function for all your above addSubview calls. It adds a subview inside another view by stretching the subview edge to edge in it (full width & height).

public static func add(_ subView: UIView, in containerView: UIView) {
    containerView.addSubview(subView)
    subView.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        subView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
        subView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
        subView.topAnchor.constraint(equalTo: containerView.topAnchor),
        subView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor)
        ]
    )
}

Upvotes: 1

Related Questions