2014-09-24 231 views
7

我可以用下面的代碼以編程方式將WKWebView添加到子視圖。如何將WKWebView添加到通過Interface Builder添加的視圖containerView2中?WKWebView添加到子視圖

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

如果containerView2通過界面生成器和containerView創建基本上是你的WKWebViewloadView()方法可能如下:

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!) 
     } 
    } 
相關問題