首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

SwiftUI : WKWebView有没有办法在WKWebView加载完成后调用函数?

在SwiftUI中,可以使用WKWebView来加载网页内容。要在WKWebView加载完成后调用函数,可以通过WKNavigationDelegate来实现。

首先,需要创建一个自定义的WKWebViewWrapper,用于包装WKWebView,并设置其navigationDelegate为自身。然后,在WKWebViewWrapper中实现WKNavigationDelegate的相关方法。

以下是一个示例代码:

代码语言:txt
复制
import SwiftUI
import WebKit

struct ContentView: View {
    var body: some View {
        WebView(url: "https://www.example.com")
    }
}

struct WebView: UIViewRepresentable {
    let url: String
    
    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView()
        webView.navigationDelegate = context.coordinator
        webView.load(URLRequest(url: URL(string: url)!))
        return webView
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {
        // 更新视图
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    class Coordinator: NSObject, WKNavigationDelegate {
        let parent: WebView
        
        init(_ parent: WebView) {
            self.parent = parent
        }
        
        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            // 在WKWebView加载完成后调用函数
            parent.webViewDidFinishLoading()
        }
    }
    
    func webViewDidFinishLoading() {
        // 在加载完成后执行的函数
        print("WebView加载完成")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

在上述代码中,我们创建了一个名为WebView的UIViewRepresentable,用于在SwiftUI中使用WKWebView。在makeUIView方法中,我们创建了一个WKWebView,并设置其navigationDelegate为自身。在Coordinator类中,我们实现了WKNavigationDelegate的webView(_:didFinish:)方法,在WKWebView加载完成后调用了父视图的webViewDidFinishLoading函数。

这样,当WKWebView加载完成后,会调用webViewDidFinishLoading函数,你可以在该函数中执行你想要的操作。

推荐的腾讯云相关产品:腾讯云移动浏览器网页开发服务(https://cloud.tencent.com/product/mbs)

请注意,以上答案仅供参考,具体实现方式可能因不同的需求和场景而有所变化。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券