我在我的应用程序中使用WKWebView,每当我旋转设备时,webView中的内容都会移动。然后,当我向后旋转时,内容再次移动,但不会移动到原来的位置。我试图在iOS上感受Safari,但网站不能在WKWebView中正确缩放和旋转。
override func viewDidLoad() {
super.viewDidLoad()
let request = URLRequest(url: URL(string: "https://www.hackster.io/projects")!)
let config = WKWebViewConfiguration()
let content = WKUserContentController()
content.addUserScript(WKUserScript(source: try! String(contentsOfFile: Bundle.main.path(forResource: "script.js", ofType: nil)!), injectionTime: .atDocumentEnd, forMainFrameOnly: true))
config.userContentController = content
webView = WKWebView(frame: view.frame, configuration: config)
webView.navigationDelegate = self
webView.allowsBackForwardNavigationGestures = true
webView.load(request)
view.addSubview(webView)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animate(alongsideTransition: { (context) in
self.webView.frame = CGRect(origin: CGPoint.zero, size: size)
}, completion: nil)
}
然后script.js文件包含此内容。
var m = document.createElement("meta")
m.setAttribute("name", "viewport")
m.setAttribute("content", "width=device-width, initial-scale=1.0, user-scalable=yes")
document.getElementsByTagName("head")[0].appendChild(m)
script.js仅用于允许缩放。