WebView 在加载网站时如何向它添加 ActivityIndicator(旋转轮)?
这是 WebView 的代码:
import Foundation
import SwiftUI
import WebKit
struct WebView : UIViewRepresentable {
var url: String
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
}
func updateUIView(_ uiView: WKWebView, context: UIViewRepresentableContext <WebView>) {
}
}
这是在另一个视图中显示 WebView 并告诉它要加载的 URL 的代码:
WebView(url: "https://www.google.com")
谢谢!
编辑:在另一个视图中调用 WebView 时,我必须能够将 URL 作为字符串传递,如上所示。这样我可以很容易地告诉 WebView 要加载哪个 URL,并将 WebView() 的两个实例放在一起显示不同网站的视图中,如下所示:
VStack {
WebView(url: "https://www.google.com")
WebView(url: "https://www.bing.com")
}
回答1
您可以使用以下代码,它包含“UIActivityIndicatorView”并使用“WKNavigationDelegate”处理
import WebKit
import SwiftUI
struct Webview: UIViewRepresentable {
let url: URL
var activityIndicator: UIActivityIndicatorView! = UIActivityIndicatorView(frame: CGRect(x: (UIScreen.main.bounds.width / 2) - 30, y: (UIScreen.main.bounds.height / 2) - 30, width: 60, height: 60))
func makeUIView(context: Context) -> UIView {
let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
let webview = WKWebView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
webview.navigationDelegate = context.coordinator
let request = URLRequest(url: self.url, cachePolicy: .returnCacheDataElseLoad)
webview.load(request)
view.addSubview(webview)
activityIndicator.backgroundColor = UIColor.gray
activityIndicator.startAnimating()
activityIndicator.color = UIColor.white
activityIndicator.layer.cornerRadius = 8
activityIndicator.clipsToBounds = true
view.addSubview(activityIndicator)
return view
}
func updateUIView(_ webview: UIView, context: UIViewRepresentableContext<Webview>) {
}
func makeCoordinator() -> WebViewHelper {
WebViewHelper(self)
}
}
class WebViewHelper: NSObject, WKNavigationDelegate {
var parent: Webview
init(_ parent: Webview) {
self.parent = parent
super.init()
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
parent.activityIndicator.isHidden = true
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
parent.activityIndicator.isHidden = true
print("error: \(error)")
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
parent.activityIndicator.isHidden = true
print("error \(error)")
}
}