SwiftUI 的一个技术问题

2022-12-19 20:15:55 +08:00
 wseani

我有一个需要加载数据的 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)
                 }
            }
         }
    }
}
617 次点击
所在节点    问与答
2 条回复
hstdt
2022-12-20 13:52:49 +08:00
```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)
}
}
}
```
wseani
2022-12-20 15:27:09 +08:00
@hstdt 多谢,我用类似的方式解决了,代码如下:
```lang-swift
@MainActor
class Model: ObservableObject {
@Published var progress: Int = 0

func fetchData() async {
for idx in 0...100 {
await load_data(idx)
progress += 1
}
}

func load_data() async {
// 加载大文件数据
}
}
```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/903580

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX