WKWebView ScaleToFit

痞子三分冷 提交于 2019-12-19 09:52:28

问题


Moving from UIWebView to WKWebView, I can not figure out how to make the HTML that I am loading using the loadHTMLString function on WKWebView size to fit the view bounds. I now get the html to load but it goes off the right and bottom of my view. How do I scale it to fit my view bounds?


回答1:


First of all, take a container view in StoryBoard under which you are going to add the WKWebView as a subview:

@IBOutlet var container: UIView!

then import WebKit and initialize it and later add as the subview of the container. In order to preserve the bound you have to give it constraint value according to its parent view. This is how I have done it:

        let webView = WKWebView(frame: .zero)
        container.addSubview(webView)

        webView.translatesAutoresizingMaskIntoConstraints = false
        let height = NSLayoutConstraint(item: webView, attribute: .height, relatedBy: .equal, toItem: container, attribute: .height, multiplier: 1, constant: 0)
        let width = NSLayoutConstraint(item: webView, attribute: .width, relatedBy: .equal, toItem: container, attribute: .width, multiplier: 1, constant: 0)
        let leftConstraint = NSLayoutConstraint(item: webView, attribute: .leftMargin, relatedBy: .equal, toItem: container, attribute: .leftMargin, multiplier: 1, constant: 0)
        let rightConstraint = NSLayoutConstraint(item: webView, attribute: .rightMargin, relatedBy: .equal, toItem: container, attribute: .rightMargin, multiplier: 1, constant: 0)
        let bottomContraint = NSLayoutConstraint(item: webView, attribute: .bottomMargin, relatedBy: .equal, toItem: container, attribute: .bottomMargin, multiplier: 1, constant: 0)
        container.addConstraints([height, width, leftConstraint, rightConstraint, bottomContraint])

        let myURL = URL(string: "")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)

add the desired url and you are done.



来源:https://stackoverflow.com/questions/35568868/wkwebview-scaletofit

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