如何自动定标WKWebView的内容? [英] How to autoscale the contents of a WKWebView?
本文介绍了如何自动定标WKWebView的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
要在Swift中使用旧的WebView自动缩放网页,我所要做的就是:
To autoscale a webpage inside a good old WebView in Swift, all I had to do was:
var w:UIWebView
w.scalesPageToFit=true
我找不到WKWebView和网页的等效方法在我的应用中看起来太大了。如何自动调整WKWebView的内容?
I cannot find an equivalent method for a WKWebView, and webpages appear too big in my app. How can I autoscale the contents of a WKWebView?
- 我正在使用Xcode 7和Swift
-I am using Xcode 7 and Swift
推荐答案
这是我的解决方案:
extension WKWebView {
private struct key {
static let scale = unsafeBitCast(Selector("scalesPageToFit"), UnsafePointer<Void>.self)
}
private var sourceOfUserScript: String {
return "(function(){\n" +
" var head = document.getElementsByTagName('head')[0];\n" +
" var nodes = head.getElementsByTagName('meta');\n" +
" var i, meta;\n" +
" for (i = 0; i < nodes.length; ++i) {\n" +
" meta = nodes.item(i);\n" +
" if (meta.getAttribute('name') == 'viewport') break;\n" +
" }\n" +
" if (i == nodes.length) {\n" +
" meta = document.createElement('meta');\n" +
" meta.setAttribute('name', 'viewport');\n" +
" head.appendChild(meta);\n" +
" } else {\n" +
" meta.setAttribute('backup', meta.getAttribute('content'));\n" +
" }\n" +
" meta.setAttribute('content', 'width=device-width, user-scalable=no');\n" +
"})();\n"
}
var scalesPageToFit: Bool {
get {
return objc_getAssociatedObject(self, key.scale) != nil
}
set {
if newValue {
if objc_getAssociatedObject(self, key.scale) != nil {
return
}
let time = WKUserScriptInjectionTime.AtDocumentEnd
let script = WKUserScript(source: sourceOfUserScript, injectionTime: time, forMainFrameOnly: true)
configuration.userContentController.addUserScript(script)
objc_setAssociatedObject(self, key.scale, script, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
if URL != nil {
evaluateJavaScript(sourceOfUserScript, completionHandler: nil)
}
} else if let script = objc_getAssociatedObject(self, key.scale) as? WKUserScript {
objc_setAssociatedObject(self, key.scale, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
configuration.userContentController.removeUserScript(script)
if URL != nil {
let source = "(function(){\n" +
" var head = document.getElementsByTagName('head')[0];\n" +
" var nodes = head.getElementsByTagName('meta');\n" +
" for (var i = 0; i < nodes.length; ++i) {\n" +
" var meta = nodes.item(i);\n" +
" if (meta.getAttribute('name') == 'viewport' && meta.hasAttribute('backup')) {\n" +
" meta.setAttribute('content', meta.getAttribute('backup'));\n" +
" meta.removeAttribute('backup');\n" +
" }\n" +
" }\n" +
"})();"
evaluateJavaScript(source, completionHandler: nil)
}
}
}
}
}
extension WKUserContentController {
public func removeUserScript(script: WKUserScript) {
let scripts = userScripts
removeAllUserScripts()
scripts.forEach {
if $0 != script { self.addUserScript($0) }
}
}
}
这篇关于如何自动定标WKWebView的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文