如何知道我的 WKWebview 派生子视图何时加载 Swift

How to know when my WKWebview derived subview is loaded in Swift

我有一个视图,它在 viewDidLoad() 方法中发生某些操作后加载子视图:

   override func viewDidLoad() {
        super.viewDidLoad()
        //OTHER STUFF...
        let config = WKWebViewConfiguration()
        config.userContentController = contentController
        self.myWebView = WKWebView(
            frame: self.containerView.bounds,
            configuration: config
        )
        self.myWebView.navigationDelegate = self
        self.view.addSubview(self.myWebView)
    }

加载网络视图后,我需要进行一些检查。我该怎么做:

webSubviewDidLoad() {
    //do stuff
}

有一个特定的委托 didFinishNavigation

didFinishNavigation documentation

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let configuration = WKWebViewConfiguration()
        let webView = WKWebView(frame: .zero, configuration: configuration)
        webView.translatesAutoresizingMaskIntoConstraints = false
        webView.navigationDelegate = self
        view.addSubview(webView)

        /* add layout constraints that make the webview fitting in your view */

        if let url = URL(string: "https://google.com") {
            webView.load(URLRequest(url: url))
        }
    }

}

  extension ViewController: WKNavigationDelegate {

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("Finished navigating to url \(webView.url)")
    }

}

或者您可以检查 estimatedProgress 属性 的进度

estimatedProgress documentation

第 1 步。添加一个观察者,以便在您的 Web 视图完成加载时收到通知,如下所示。此代码应放在视图控制器的 viewDidLoad 方法中 class.

myWebView.addObserver(self, forKeyPath: #keyPath(WKWebView.isLoading), options: .new, context: nil)

第 2 步。在您的视图控制器中实现 observeValue(forKeyPath:) 方法,执行您需要执行的任何操作,如下所示。

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "isLoading" && !myWebView.isLoading {
        // Do your needed action here
    }
}

实现自己的 WebView:

import WebKit

protocol WebViewDelegate {
    func didLayoutSubviews()
}

class WebView : WKWebView {
    
    weak var delegate: WebViewDelegate?
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.delegate?.didLayoutSubviews()
    }
}