2017-11-18 20 views
0

我需要一些幫助。 我想在第一個視圖控制器中的webView完成後在第二個視圖控制器中預載我的webView。Swift 3:預先加載SecondViewController的WKWebView提前點擊

我相信我需要使用通知中心post/observe在我的第二個視圖控制器中調用我的loadWebView函數,但不知道如何。任何建議表示讚賞。


enter image description here

FirstViewController.swift

import UIKit; 
import WebKit; 

class FirstViewController: UIViewController, WKNavigationDelegate { 


    let webView:WKWebView = WKWebView(frame: CGRectMake(0, 0, UIScreen.main.bounds.width, UIScreen.main.bounds.height)) 

    func webView(_ webView: WKWebView, 
      didFinish navigation: WKNavigation!) { 
     print("loaded!") 
     webView.isHidden = false 

     } 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     let url = URL(string: "https://www.google.com") 
     webView.navigationDelegate = self 
     webView.load(URLRequest(url: url!)) 
     webView.isHidden = true 
     self.view.addSubview(webView) 

    } 

} 

SecondViewController.swift

import UIKit 
import WebKit 

class SecondViewController: UIViewController, WKNavigationDelegate { 

    let webView:WKWebView = WKWebView(frame: CGRectMake(0, 0, UIScreen.main.bounds.width, UIScreen.main.bounds.height)) 


    func webView(_ webView: WKWebView, 
      didFinish navigation: WKNavigation!) { 
     print("loaded!") 
     webView.isHidden = false 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 


    } 

    func loadWebView() { 
     let url = URL(string: "https://www.amazon.com") 
     webView.navigationDelegate = self 
     webView.load(URLRequest(url: url!)) 
     webView.isHidden = true 
     self.view.addSubview(webView) 
    } 


} 

回答

0

在第一個VC:

func webView(_ webView: WKWebView, 
      didFinish navigation: WKNavigation!) { 

    //Post notification 
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "WebViewFinishedLoading"), object: nil) 
} 

在二VC:

override func viewDidLoad() { 
     super.viewDidLoad() 

    // Add observer for your notification 
    NotificationCenter.default.addObserver(self, selector: #selector(loadWebView), name: NSNotification.Name(rawValue: "WebViewFinishedLoading"), object: nil) 
    } 

//Remove observer in deinit 
deinit {  
    NotificationCenter.default.removeObserver(self) 
} 
+0

如果secondViewController是不是在堆棧呢? –

+0

在初始化之前,您無法加載它。你到底在做什麼? –