How to autoscale the contents of a WKWebView?

你说的曾经没有我的故事 提交于 2019-12-06 06:46:38

问题


To autoscale a webpage inside a good old WebView in Swift, all I had to do was:

var w:UIWebView
w.scalesPageToFit=true

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?

-I am using Xcode 7 and Swift


回答1:


Here is my solution:

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



回答2:


This worked for me, if there is an easier or cleaner way, let us know. In this example I resize the WKWebview everytime the device's screen orientation changes, place the code in your ViewController. In my case the website I loaded could already autosize itself in a browswer, and with this code, it will also resize inside a 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
        }


来源:https://stackoverflow.com/questions/32821677/how-to-autoscale-the-contents-of-a-wkwebview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!