Programmatically WKwebView inside an UIView with auto layout

autolayoutconstraintsuiviewwkwebview

This is probably something easy for some expert, so. the thing is theres no WKWebView in Xcode visual interface for storyboard use, as opposed to UIWebview, so it has to be created programmatically . im using a nav controller for my whole app.

I created a VIEW in story board and used auto layout to constraint 0,0,0,0. so will like to add the WKWebView to that view "Daview". as a subview and fill it completely . i can't seem to figure it out.

Please take a look at the code Below

class ViewController2: UIViewController ,WKNavigationDelegate {

    @IBOutlet weak var navigation: UINavigationItem!

    @IBOutlet var daview: UIView!
    var restWeb: WKWebView?

    @IBOutlet var BottomView: UIView!

   // var ActivityIndicator =  UIActivityIndicatorView()


     override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(true)       
         println(" daview bounds in VIEWDIDAPPEAR is \(self.daview.bounds) y Frame \(self.daview.frame)")
       restWeb!.bounds = daview.bounds
    }



    override func viewDidLoad() {
        super.viewDidLoad()

        /* Create our preferences on how the web page should be loaded */
        let preferences = WKPreferences()
        preferences.javaScriptEnabled = true

        /* Create a configuration for our preferences */
        let configuration = WKWebViewConfiguration()
        configuration.preferences = preferences


        /* Now instantiate the web view */
        restWeb = WKWebView(frame: self.daview.bounds, configuration: configuration)

   let urlString = "http://www.google.com"  


        println("EL DETAIL URL es \(urlString)")
        if let theWebView = restWeb {
            println("Existe restWeb")
        let urlRest = NSURL(string:urlString)
        let requestRest = NSURLRequest(URL: urlRest!)
        theWebView.loadRequest(requestRest)
        theWebView.allowsBackForwardNavigationGestures = true
        theWebView.navigationDelegate = self
        self.daview.addSubview(theWebView)
        }


} // finish viewdidload

Best Answer

One line answer: Move you code from viewDidLoad() to viewDidAppear()

Explanation: I'm no expert, but I have faced this problem in my early days. The problem with your webview is that you are trying to set the bounds in viewDidLoad()

    restWeb = WKWebView(frame: self.daview.bounds, configuration: configuration)

But, the autolayout is complete only when the view has appeared. Means, the bounds (self.daview.bounds) you are trying to use in viewDidLoad, give you a value even before the view layout is set.

Solution: The correct auto-layout-bounds are available in and after viewDidAppear. If you move your code

WKWebView(frame: self.daview.bounds, configuration: configuration)

from viewDidLoad() to viewDidAppear(), then all your wishes will come true.