【问题标题】:ProgressView in SwiftUI 2.0 (How to display the ProgressView during an operation)SwiftUI 2.0 中的 ProgressView(如何在操作过程中显示 ProgressView)
【发布时间】:2020-09-06 01:26:24
【问题描述】:

我正在尝试显示 ProgressView,同时正在处理某些内容,并且应用程序正忙。

在这个例子中,for期间

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

【问题讨论】:

  • 您的代码不起作用吗?会发生什么?
  • 代码运行了,但是没有出现ProgressView
  • 编译器可能优化了 for 循环,所以它太快了。如果注释掉行设置isLoading = false,会出现进度视图吗?
  • 是的,但是在打印之后
  • 状态变化不是瞬时的。可能是您正在使用的任务太快了。更好的测试可能是DispatchQueue.main.asyncAfter

标签: ios swift swiftui xcode12 swiftui-environment


【解决方案1】:

您刚刚使用同步长按钮操作阻塞了 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)
        }
    }
}

【讨论】:

  • 这个,有点用,但应用程序在 for 期间不忙,我需要应用程序在工作期间忙
猜你喜欢
  • 1970-01-01
  • 2023-02-26
  • 2022-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多