首页 > 解决方案 > SwiftUI在Thread中更新progressBar

问题描述

我正在尝试管理与 SwiftUI 的聊天。

我发现了一个CircularProgressBar可以与 SwiftUI 一起使用,在示例中,它与Timer. 如果我使用 Zip 提取更改计时器,则 UI 不会更新。

struct DetailView: View {
    var selectedChat: Chat?

    @State var progressBarValue:CGFloat = 0

    var body: some View {
        Group {
            if selectedChat != nil {
                VStack {
                    if progressBarValue < 1 {
                        CircularProgressBar(value: $progressBarValue)
                    }
                    else {
                        //Text("WELL DONE")
                        Text("\(UserData().getChat(withID: selectedChat!.id)!.allText.first!.text)")
                    }
                }
            } else {
                VStack {
                    CircularProgressBar(value: $progressBarValue)
                    Text("Detail view content goes here")
                }
            }
        }.navigationBarTitle(Text("\(selectedChat?.name ?? "")"))
        .onAppear {

            if let chat = self.selectedChat {
                if chat.allText.count == 0 {
                    let exData = ExtractData()
                    if let path = chat.getUnzipPath()?.relativePath {
                        DispatchQueue.main.async {//with or without the behavior is the same
                            exData.manageExtractedZip(unzipPath: path) { progress in
                                if progress >= 1 {
                                    var newChat = chat
                                    newChat.allText = exData.allTexts
                                    let userD = UserData()
                                    userD.overrideChat(with: newChat)
                                    print(exData.allTexts)
                                }
                                self.progressBarValue = CGFloat(progress)
                                print("progressBarValue: \(self.progressBarValue)") //This is printing well
                            }
                        }
                    }

                }
                else {
                    self.progressBarValue = 1
                }
            }
            /* This is working
            Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { timer in
                self.progressBarValue += 0.1
                print(self.progressBarValue)
                if (self.progressBarValue >= 1) {
                    timer.invalidate()
                }
            }*/
        }
    }

}

struct DetailView_Previews: PreviewProvider {
    static var previews: some View {
        DetailView(selectedChat: UserData().chatData.first!)
    }
}

如何让它发挥作用?

标签: iosswiftiphonexcodeswiftui

解决方案


推荐阅读