我在WKWebView中托管了一些第三方内容,它们的内容在方向更改时无法正确调整大小。不过,在Safari中它的大小确实正确。
window.onresize = function() { console.log(window.innerWidth) }
相同的
每次宽度(768),不考虑方向,但当我评估
window.innerWidth
旋转完成后,在控制台上打印正确的宽度。
这是已知的问题吗?有什么解决办法吗?
我最后做的是重新发射
resize
延迟后的事件。它很难看,但它解决了我的用例。
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: nil) { _ in
// Orientation change triggers the `resize` event, but `window.innerWidth` is
// wrong *during that time*. By calling resize a second time, we let content resize itself
// according to the correct dimensions.
// There's more! Sometimes the dimensions are still wrong after the rotation has completed,
// so we have to wait. The minimum reliable delay varies widely across devices.
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(750)) {
self.webView?.evaluateJavaScript("window.dispatchEvent(new Event('resize'));", completionHandler: nil)
}
}
}