本文介绍了WKWebView添加到SubView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

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

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)
    }

当然,您可以为您的观点提供更好的名称。例如,parent元素可以被称为 containerView ,你的 WKWebView 可以被称为 webView的。通过这种方式,代码变得更具可读性:

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!)
        }
    }

这篇关于WKWebView添加到SubView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 15:43