Hello Worl" /> Hello Worl" /> Hello Worl"/>

Swift - WKWebView is not shown at all

76 views Asked by At

I have a simple WKWebView which is not shown at all in my app.

This is the code:

var contentWKWebView = WKWebView()
let html = "<html><body>Hello World</body></html>"
contentWKWebView.loadHTMLString(html, baseURL: Bundle.main.bundleURL)
self.addSubview(contentWKWebView)
contentWKWebView.translatesAutoresizingMaskIntoConstraints = false
contentWKWebView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 5).isActive = true
contentWKWebView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -5).isActive = true
contentWKWebView.topAnchor.constraint(equalTo: stackView.bottomAnchor, constant: 10).isActive = true
contentWKWebView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -10).isActive = true

The web view is not shown at all.

Notes:

  1. This code is part of a UITableCellView code inside a UITableView.

  2. This code is located in a separate Model Swift file and not directly under the ViewController Swift file.

  3. The imports in this Swift file are:

import Foundation

import UIKit

import WebKit

  1. There are other objects in the UITableCellView which preceded the WKWebView (StackView, Label, etc.) which are shown correctly.

Any idea?

Thanks! AJ

1

There are 1 answers

0
AJ Gottes On

The problem was that I missed the line:

var contentWKWebView = WKWebView()

This line was at the beginning of the TableCellView, before the init func. The correct behaviour is to out this line inside: func layoutSubviews()

Moreover, I think it is better to make a UIView and put the WKWebView inside it which stick to its bounds. There was indeed also trouble with the constraints.

Thank you guy for opening my mind.

AJ