Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a sized WKWebView in Swift 3 / iOS 10

I am attempting to add a WKWebView to my app that takes up about ~2/3 of the screen (leaving space at the bottom). Because there seems to be no way to add the WKWebView to the storyboard, I added a regular UIView. Then in my viewDidAppear method I try and create a WKWebView with the same bounds. Is this a sound approach?

My code looks like this:

    @IBOutlet var conversationView: UIView!

    override func viewDidAppear(_ animated: Bool) {
      let webView = WKWebView(frame: conversationView.frame)
      if let url = URL(string: "https://www.google.com") {
        webView.load(URLRequest(url: url))
      }

      // conversationView = webView // <-- doesn't work :\
      conversationView.addSubview(webView) // works!
    }

Swaping the views outright doesn't work at all, so instead I add the web view as a subview of the temporary view I added to the storyboard. This at least lets me constrain it's position and size but still it feels very kludgy and like there must be a better way of doing this..

Screenshot

like image 462
speg Avatar asked Nov 29 '16 00:11

speg


1 Answers

None of the other answers worked for me. The answer by Samip Shah is along the right track but the constraints are not quite correct. The important thing to remember is to set translatesAutoresizingMaskIntoConstraints to false.

So, here's my solution. In the storyboard create a UIView with the constraints and layout you want for the WKWebView. In your view controller add the code:

@IBOutlet var contentView: UIView!
var wkWebView:WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    wkWebView = WKWebView(frame:contentView.frame)
    contentView.addSubview(wkWebView)
    constrainView(view: wkWebView, toView: contentView)

    let request = URLRequest(url: /* your url here */)
    wkWebView.load(request)
}

The code for constraining the view. You might add this to a utilities class if you want to use it more than one view controller.

func constrainView(view:UIView, toView contentView:UIView) {
    view.translatesAutoresizingMaskIntoConstraints = false
    view.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
    view.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
    view.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
    view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
}
like image 132
Dale Avatar answered Nov 15 '22 12:11

Dale