我可以使用以下代码以编程方式将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.
}
}
答案 0 :(得分:7)
如果通过界面生成器创建了containerView2
,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!)
}
}