在进程仍在运行时在SwiftUI中更新文本

问题描述 投票:0回答:2

我喜欢在屏幕上更新文本以通知用户进度。我在SwiftUI中使用Text。每当我更改此消息时,即使该进程仍在运行,也应该对其进行更新。例如:

@State private var message = "-"

    var body: some View {

        VStack {
            Button("Run") {
                print("Tapped!")
                for i in 0 ... 100 {
                    self.message = "\(i)"
                    for _ in 1...1000 {
                        print(".")  // some time consuming stuff
                    }
                }
            }

            Text(message)
                .frame(width: 100)
                .padding()
        }
        .padding(40)
    }

当我更改消息时,它应该正在更新屏幕。不幸的是,循环结束后,它仅更新文本,因此显示为100。应显示为1,2,... 100。

我是否需要特殊的棘手队列,例如在使用“ DispatchQueue.main.async”的经典开发中,还是在SwiftUI中有更简单的方法?

text queue swiftui screen updating
2个回答
0
投票

swift对于仅打印1000条语句来说太快了...

顺便说一下,耗时的东西应该始终不在主线程上完成,UI Stuff应该始终在主线程上完成;)

尝试一下

struct ContentView: View {
    @State private var message = "-"

    var body: some View {

        VStack {
            Button("Run") {
                print("Tapped!")
                OperationQueue().addOperation {
                    for i in 0 ... 100 {

                        OperationQueue.main.addOperation {
                            self.message = "\(i)"
                        }
                        sleep(1)
                    }

                }
            }

            Text(message)
                .frame(width: 100)
                .padding()
        }
        .padding(40)
    }
}

0
投票

我更喜欢DispatchQueue,所以有些替代

Button("Run") {
    print("Tapped!")
    DispatchQueue.global(qos: .background).async {
        for i in 0 ... 100 {
            DispatchQueue.main.asych {
                self.message = "\(i)"
            }
            for _ in 1...1000 {
                print(".")  // some time consuming stuff
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.