效果
实现方式
为了方便使用,采用ViewModifier的方式
一、创建ViewModeifier
struct Loading: ViewModifier {
static let showNotification = Notification.Name("Loading.showNotification")
static let hidenNotification = Notification.Name("Loading.hidenNotification")
@State private var isContentShowing = false
@State private var isPresented = false
var touchable = false
func body(content: Content) -> some View {
ZStack {
content
if isPresented {
ProgressView()
.tint(Color.white)
.padding(20)
.background(Color.black.opacity(0.7))
.cornerRadius(8)
}
}.onAppear(perform: {
isContentShowing = true
}).onDisappear(perform: {
isContentShowing = false
}).onReceive(NotificationCenter.default.publisher(for: Loading.showNotification)) { output in
guard isContentShowing else {
return
}
isPresented = true
}.onReceive(NotificationCenter.default.publisher(for: Loading.hidenNotification)) { output in
guard isContentShowing else {
return
}
isPresented = false
}
}
static func show() {
NotificationCenter.default.post(name: Loading.showNotification, object: nil)
}
static func hidden() {
NotificationCenter.default.post(name: Loading.hidenNotification, object: nil)
}
}
二、扩展View
extension View {
func loadingable() -> some View {
return self.modifier(Loading())
}
}
使用
var body: some View {
VStack {
Spacer()
Button("展示") {
Loading.show()
}
Spacer()
Button("隐藏") {
Loading.hidden()
}
Spacer()
}.loadingable()
}