WKWebView ScaleToFit

2019-02-27 06:11发布

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条回答
聊天终结者
2楼-- · 2019-02-27 06:30

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.

查看更多
登录 后发表回答