12

我可以使用下面的代码以编程方式将 WKWebView 添加到子视图。如何将 WKWebView 添加到通过 Interface Builder 添加的视图 containerView2?

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.
}
}
4

1 回答 1

7

IfcontainerView2是通过 Interface Builder 创建的,containerView基本上你的WKWebView loadView()方法可能如下所示:

    override func loadView() {
        super.loadView()

        webView = WKWebView()
        containerView = self.webView!

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

当然,你可以为你的观点取更好的名字。例如,“父”元素可以被调用containerView,而你的元素可以被WKWebView调用webView。通过这种方式,代码变得更具可读性:

    override func loadView() {
        super.loadView()

        webView = WKWebView()

        if (webView != nil) {
            webView!.frame = containerView.frame
            containerView.addSubview(webView!)
        }
    }
于 2015-11-17T22:46:05.820 回答