以编程方式在具有自动布局的UIView内部使用WKwebView

lor*_*lez 3 constraints uiview autolayout wkwebview

这对某些专家来说可能很容易,所以.Xcode可视化界面中没有用于故事板使用的WKWebView,而不是UIWebview,因此必须以编程方式创建.我使用导航控制器为我的整个应用程序.

我在故事板中创建了一个VIEW,并使用自动布局来约束0,0,0,0.所以想将WKWebView添加到该视图"Daview".作为子视图并完全填写.我似乎无法弄明白.

请看下面的代码

class ViewController2: UIViewController ,WKNavigationDelegate {

    @IBOutlet weak var navigation: UINavigationItem!

    @IBOutlet var daview: UIView!
    var restWeb: WKWebView?

    @IBOutlet var BottomView: UIView!

   // var ActivityIndicator =  UIActivityIndicatorView()


     override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(true)       
         println(" daview bounds in VIEWDIDAPPEAR is \(self.daview.bounds) y Frame \(self.daview.frame)")
       restWeb!.bounds = daview.bounds
    }



    override func viewDidLoad() {
        super.viewDidLoad()

        /* Create our preferences on how the web page should be loaded */
        let preferences = WKPreferences()
        preferences.javaScriptEnabled = true

        /* Create a configuration for our preferences */
        let configuration = WKWebViewConfiguration()
        configuration.preferences = preferences


        /* Now instantiate the web view */
        restWeb = WKWebView(frame: self.daview.bounds, configuration: configuration)

   let urlString = "http://www.google.com"  


        println("EL DETAIL URL es \(urlString)")
        if let theWebView = restWeb {
            println("Existe restWeb")
        let urlRest = NSURL(string:urlString)
        let requestRest = NSURLRequest(URL: urlRest!)
        theWebView.loadRequest(requestRest)
        theWebView.allowsBackForwardNavigationGestures = true
        theWebView.navigationDelegate = self
        self.daview.addSubview(theWebView)
        }


} // finish viewdidload
Run Code Online (Sandbox Code Playgroud)

Nis*_*ant 12

一行答案:将代码从viewDidLoad()移到viewDidAppear()

说明:我不是专家,但我早年遇到过这个问题.您的webview的问题是您正在尝试在viewDidLoad()中设置边界

    restWeb = WKWebView(frame: self.daview.bounds, configuration: configuration)
Run Code Online (Sandbox Code Playgroud)

但是,只有在视图出现时才会完成自动布局.意味着,您尝试在viewDidLoad中使用的边界(self.daview.bounds)甚至在设置视图布局之前为您提供值.

解决方案:viewDidAppear中和之后可以使用正确的自动布局边界.如果您移动代码

WKWebView(框架:self.daview.bounds,配置:配置)

从viewDidLoad()到viewDidAppear(),那么你的所有愿望都会实现.