WKWebView content not changing correctly
I have WKWebView
one that loads HTML5 games. HTML5 games resize beautifully when opened in safari on my Mac, no problem. However, when I change the orientation of my iPad Pro and UICollectionViewCells
resize WebView
, the containing WKWebView
is also resized. Unfortunately not a game.
In the image below, I've given a WKWebView
backgroundColor UIColor.red
so it's easy to distinguish.
This is my code:
import UIKit
import WebKit
final class WebView: UIView {
var webView: WKWebView!
var bounces: Bool = true {
didSet {
webView.scrollView.bounces = bounces
}
}
override var bounds: CGRect {
didSet {
if webView != nil {
var b = bounds
b.origin.x = 0
b.origin.y = 0
webView.bounds = b
webView.frame = b
}
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: 100), configuration: webConfiguration)
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
webView.navigationDelegate = self
webView.backgroundColor = UIColor.red
addSubview(webView)
}
override func draw(_ rect: CGRect) {
webView.frame = rect
}
/// Load request
func load(_ request: URLRequest) {
webView.load(request)
}
}
What am I doing wrong, or better yet ... how can I show the WKWebView to resize without reloading the webview.
Update:
If I lock the device (on / off button) and unlock the device by resuming, the content changes correctly and looks correct.
Update: Content changes significantly as the
size is reduced UICollectionViewCell
. But this is not when increasing the size.
Also tried resizing the subclasses, which didn't help either:
override var bounds: CGRect {
didSet {
if webView != nil {
var b = bounds
b.origin.x = 0
b.origin.y = 0
webView.bounds = b
webView.frame = b
for item in webView.subviews {
item.bounds = b
if item.subviews.count > 0 {
setBounds(toSubView: item, toBounds: b)
}
}
}
}
}
func setBounds(toSubView subView: UIView, toBounds bounds: CGRect) {
for item in subView.subviews {
if item.subviews.count > 0 {
setBounds(toSubView: item, toBounds: bounds)
}
if item.classIdentifier == "WKContentView" {
item.bounds = bounds
}
}
}
source to share
No one has answered this question yet
Check out similar questions: