Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WKWebView Add to SubView

I can add a WKWebView programmatically to a subview with the code below. How can I add WKWebView to the view containerView2 that was added via Interface Builder?

import UIKit
import WebKit

class ViewController: UIViewController {

@IBOutlet var containerView : UIView?
@IBOutlet weak var containerView2: UIView!

var webView: WKWebView?

override func loadView() {

    super.loadView()

    self.webView = WKWebView()

    self.webView?.frame = CGRectMake(50, 50, 200, 200)
    self.webView?.sizeToFit()
    self.containerView = self.webView!
    //how can I set a View (containerView2) added by Interface Builder =  to self.webView!

    self.view.addSubview(self.containerView!)
}

override func viewDidLoad() {
    super.viewDidLoad()

    var url = NSURL(string:"http://www.google.com")
    var req = NSURLRequest(URL:url)
    self.webView!.loadRequest(req)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}
like image 906
user1594257 Avatar asked Sep 24 '14 21:09

user1594257


1 Answers

If containerView2 is created via Interface Builder and containerView is basically your WKWebView loadView() method might look like:

    override func loadView() {
        super.loadView()

        webView = WKWebView()
        containerView = self.webView!

        containerView.frame = containerView2.frame
        containerView2.addSubview(containerView)
    }

And of course you can have better names for your views. For example, the "parent" element could be called containerView and your WKWebView could just be called webView. In this way code becomes much more readable:

    override func loadView() {
        super.loadView()

        webView = WKWebView()

        if (webView != nil) {
            webView!.frame = containerView.frame
            containerView.addSubview(webView!)
        }
    }
like image 77
Maksim Sorokin Avatar answered Oct 28 '22 03:10

Maksim Sorokin