swift2 如何自动缩放WKWebView的内容?

bvuwiixz  于 2022-11-06  发布在  Swift
关注(0)|答案(2)|浏览(245)

要在Swift中的一个很好的旧WebView中自动缩放一个网页,我所要做的就是:

var w:UIWebView
w.scalesPageToFit=true

我找不到WKWebView的等效方法,并且网页在我的应用中显得太大。如何自动缩放WKWebView的内容?

  • 我正在使用Xcode 7和Swift
a11xaf1n

a11xaf1n1#

下面是我的解决方案:

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) }
        }
    }
}
x6492ojm

x6492ojm2#

这对我很有效,如果有更简单或更干净的方法,请告诉我们。在这个例子中,我在每次设备的屏幕方向改变时调整WKWebview的大小,将代码放在ViewController中。在我的例子中,我加载的网站已经可以在浏览器中自动调整大小,使用这段代码,它也可以在WKWebView中调整大小:

onViewDidLoad{

        // other initialization code here...

        screenWidth=UIScreen.mainScreen().bounds.width
        screenHeight=UIScreen.mainScreen().bounds.height
    }

      var screenWidth:CGFloat=0
      var screenHeight:CGFloat=0
      func resizeAccordingToOrientation(){
            if UIDevice.currentDevice().orientation.isLandscape.boolValue {
                var frame:CGRect = webView!.frame;
                frame.size = CGSizeMake(screenHeight, screenWidth-getNavBarHeight())//w,h !!!
                frame.origin.x=0
                frame.origin.y=getNavBarHeight()
                webView!.frame = frame;
                //print("Origin x: "+(webView?.frame.origin.x.description)!+" , "+(webView?.frame.origin.y.description)!)
            }
            else{
                var frame:CGRect = webView!.frame;
                frame.size = CGSizeMake(screenWidth,screenHeight-getNavBarHeight()-self.navigationController!.navigationBar.frame.origin.y)
                frame.origin.x=0
                frame.origin.y=getNavBarHeight()+self.navigationController!.navigationBar.frame.origin.y
                webView!.frame = frame;
                //print("Origin x: "+(webView?.frame.origin.x.description)!+" , "+(webView?.frame.origin.y.description)!)
            }
        }

    func getNavBarHeight() -> CGFloat{
            return self.navigationController!.navigationBar.frame.size.height
        }

相关问题