WKWebView ScaleToFit

12,203

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.

Share:
12,203
Rob
Author by

Rob

iOS App Developer Love Swift Very detail oriented Full stack developer Spoiler Alert Food Safety is my App in the App Store now!

Updated on August 27, 2022

Comments

  • Rob
    Rob almost 2 years

    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?

  • mafarja
    mafarja almost 5 years
    Worked for me. Thank you so much.
  • Fay007
    Fay007 almost 5 years
    Glad that it helped :)