我有一个需要加载数据的 Task ,想在 View 里显示进度条,但是目前 Task 并不会刷新进度条的值,该怎么做呢?
目前的是
struct ContentView: View {
@ObservedObject var model: Model
var body: some View {
VStack {
ProgressView("Downloading…", value: model.progress, total: 100)
.onAppear {
Task {
await model.fetchData()
}
}
}
}
}
//在 Model.swift 里,代码如下:
@MainActor
class Model: ObservableObject {
@Published var progress: Int = 0
func fetchData() async {
Task {
do {
for idx in 0...100 {
progress += 1
sleep(1)
}
}
}
}
}
1
hstdt 2022-12-20 13:52:49 +08:00 1
```swift
struct ContentView: View { @ObservedObject var model: Model = Model() var body: some View { VStack { ProgressView("Downloading…", value: model.progress, total: 100) .onAppear { Task { await model.fetchData() } } } } } class Model: ObservableObject { @Published var progress: Double = 0 func fetchData() async { for _ in 0...100 { await MainActor.run { // 加上 onChange 之后会提示 Publishing changes from background threads is not allowed; progress += 1 } sleep(1) } } } ``` |