问题描述
我正在尝试显示 ProgressView ,同时正在处理某些事情,而应用程序很忙。
在此示例中,
import SwiftUI
struct ContentView: View {
@State var isLoading:Bool = false
var body: some View {
ZStack{
if self.isLoading {
ProgressView()
.zIndex(1)
}
Button("New View"){
self.isLoading = true
var x = 0
for a in 0...5000000{
x += a
}
self.isLoading = false
print("The End: \(x)")
}
.zIndex(0)
}
}
}
在我的应用中,当我按下按钮时, ProgressView 不会出现
那么在for运行时如何显示 ProgressView ?
我正在使用Xcode 12
解决方法
您刚刚使用同步长按钮操作阻止了UI线程。解决方案是使其在后台运行。
这是可能的修复程序(已通过Xcode 12 / iOS 14测试):
struct ContentView: View {
@State var isLoading:Bool = false
var body: some View {
ZStack{
if self.isLoading {
ProgressView()
.zIndex(1)
}
Button("New View"){
self.isLoading = true
DispatchQueue.global(qos: .background).async {
var x = 0
for a in 0...500000 {
x += a
}
DispatchQueue.main.async {
self.isLoading = false
print("The End: \(x)")
}
}
}
.zIndex(0)
}
}
}