WKWebView更改方向后显示内容错误 [英] WKWebView displays content wrong after orientation change
问题描述
我对iOS开发相当陌生,我正在使用WKWebView
来显示使用Vimeo Player播放视频的页面.该应用启动后,无论当前处于哪个方向,它都能正确显示视图.但是,一旦更改方向,该视图要么会放大显示,要么在视频下方显示空白.
I am fairly new to iOS development and I'm using a WKWebView
to display a page that plays a video using the Vimeo Player. When the app starts up, it shows the view correctly, no matter what orientation it is currently in. However, once I change the orientation the view will either look zoomed in or has whitespace below the video.
这令人讨厌的事情是它不一致.有时,视图正确显示,有时却不正确.如果在使用该应用程序时尝试放大或缩小视图或尝试滚动视图,它通常会自行纠正,但这似乎也不是100%可靠.
The annoying thing about this is that it's not consistent. Sometimes the view displays correctly, sometimes it doesn't. If I try to zoom the view in or out or try to scroll when using the app it usually corrects itself, but even that does not seem to be 100% reliable.
一些屏幕截图(在iPad 2上进行了测试):
Some screenshots (tested on iPad 2):
横向(正确):
纵向(正确):
横向(错误):
纵向(不正确):
以及用于产生此结果的代码:
And the code used to produce this result:
import Foundation
import UIKit
import WebKit
class VideoViewController : UIViewController, WKScriptMessageHandler {
@IBOutlet var containerView : UIView! = nil
var webView: WKWebView?
override func loadView() {
super.loadView()
self.webView = WKWebView()
let contentController = WKUserContentController();
let scaleToFit = WKUserScript(source: "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width, initial-scale=1.0'); document.getElementsByTagName('head')[0].appendChild(meta);", injectionTime: WKUserScriptInjectionTime.AtDocumentStart, forMainFrameOnly: true)
contentController.addUserScript(scaleToFit)
contentController.addScriptMessageHandler(self, name: "callbackHandler")
self.view = webView!
}
override func viewDidLoad() {
super.viewDidLoad()
refreshUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func refreshUI() {
let url = NSURL(string: "https://photofactsacademy.nl/api/vp.asp?id=152839850")
let requestObj = NSURLRequest(URL: url!)
webView!.loadRequest(requestObj)
}
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if(message.name == "callbackHandler") {
print("JavaScript is sending a message \(message.body)")
}
}
}
我一直在寻找WKWebView和方向更改,但没有找到任何对我有帮助的东西.
I looked through SO for WKWebView and orientation change and didn't find anything that helped me.
我们非常感谢您的帮助.
Your help is appreciated.
推荐答案
可以尝试一下
wkWebView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
这篇关于WKWebView更改方向后显示内容错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!