在 SwiftUI 中加载网站时加载 Activity 指示器

Load an Activity Indicator while website is loading in SwiftUI

我有一个显示网络视图的基本列表。我想添加一个 activity 指示符,在网页加载时显示。这是我创建的代码。

import SwiftUI
import WebKit

struct WebView: UIViewRepresentable {
    var url: String

    // makeUIView func
    func makeUIView(context: Context) -> WKWebView {

        guard let url = URL(string: self.url) else {
            return WKWebView()
        }

        let request = URLRequest(url: url)
        let wkWebView = WKWebView()
        wkWebView.load(request)
        return wkWebView
    }

    // updateUIView func
    func updateUIView(_ uiView: WKWebView, context: Context) {
    }

}


struct WebView_Preview: PreviewProvider {
    static var previews: some View {
        WebView(url: "https://www.google.com")
    }
}

谢谢!

您需要将 Coordinator 添加到您的 UIViewRepresentable

我认为这个问题的答案给了你正确的想法。

这里有一些东西可以满足您的需求。 WebView 在 Coordinator class 中有一个委托。它改变了一个绑定,ContentView 可以对此做出适当的反应。目前它只是一个显示状态原始值的文本,但它可以替换为某种 activity 指示器。

struct ContentView: View {
    @State var urlString = ""
    @State var workState = WebView.WorkState.initial

    var body: some View {
        VStack(spacing: 20) {
            WebView(urlString: self.$urlString, workState: self.$workState)

            Button("Play") {
                self.urlString = "https://www.example.com/"
            }
            Text("Current work = " + self.workState.rawValue)
        }
    }
}

struct WebView: UIViewRepresentable {
    enum WorkState: String {
        case initial
        case done
        case working
        case errorOccurred
    }

    @Binding var urlString: String
    @Binding var workState: WorkState

    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView()
        webView.navigationDelegate = context.coordinator
        return webView
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        switch self.workState {
        case .initial:
            if let url = URL(string: self.urlString) {
                uiView.load(URLRequest(url: url))
            }
        default:
            break
        }
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    class Coordinator: NSObject, WKNavigationDelegate {
        var parent: WebView

        func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
          self.parent.workState = .working
        }

        func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
            self.parent.workState = .errorOccurred
        }

        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            self.parent.workState = .done
        }

        init(_ parent: WebView) {
            self.parent = parent
        }
    }
}