Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 455
gduh Avatar asked Jan 19 '26 21:01

gduh


1 Answers

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)
        ]
    )
}
like image 199
Ashok Avatar answered Jan 21 '26 11:01

Ashok