如何在WKWebView中添加活动指示器,该指示器将在网页加载时显示该指示器,而在加载时消失?
我看过一些旧文章,但不知道如何在SwiftUI中进行操作请参阅下面的旧解决方案之一的链接How to add Activity Indicator to WKWebView (Swift 3)
使用UIViewRepresentable
创建UIActivityIndicatorView:
您可以通过调用
startAnimating()
和stopAnimating()
方法来控制活动指示器的动画时间。要在动画停止时自动隐藏活动指示器,请将hidesWhenStopped
属性设置为true。您可以使用
color
属性设置活动指示器的颜色。
struct ActivityIndicatorView: UIViewRepresentable {
@Binding var isAnimating: Bool
let style: UIActivityIndicatorView.Style
func makeUIView(context: UIViewRepresentableContext<ActivityIndicatorView>) -> UIActivityIndicatorView {
return UIActivityIndicatorView(style: style)
}
func updateUIView(_ uiView: UIActivityIndicatorView, context: UIViewRepresentableContext<ActivityIndicatorView>) {
isAnimating ? uiView.startAnimating() : uiView.stopAnimating()
}
}
创建LoadingView
以允许您环绕视图:
struct LoadingView<Content>: View where Content: View {
@Binding var isShowing: Bool
var content: () -> Content
var body: some View {
GeometryReader { geometry in
ZStack(alignment: .center) {
self.content()
.disabled(self.isShowing)
.blur(radius: self.isShowing ? 3 : 0)
VStack {
Text("Loading...")
ActivityIndicatorView(isAnimating: .constant(true), style: .large)
}
.frame(width: geometry.size.width / 2, height: geometry.size.height / 5)
.background(Color.secondary.colorInvert())
.foregroundColor(Color.red)
.cornerRadius(20)
.opacity(self.isShowing ? 1 : 0)
}
}
}
}
然后像这样在您的视图内部使用它:
struct ContentView: View {
@State var isShowing: Bool = false
var body: some View {
LoadingView(isShowing: self.$isShowing) {
Text("Hello world")
}
}
}