0
2

More than 1 year has passed since last update.

パーセントで実行の進行状況を表示するSwfitUIの非同期処理のサンプル

Posted at

Swiftでは重たい処理での非同期処理を適切に行わないとViewが実行中に操作不能になります。
以下が簡単なサンプルです。
これを応用すれば重たい変換処理中にユーザーに進捗状況を表示できます。


struct ContentView: View {
    @State private var progress: Double = 0.0
    
    var body: some View {
        VStack {
            Text("\(Int(progress * 100))%")
                .font(.title)
                .padding()
            
            ProgressView(value: progress, total: 100.0)
                .progressViewStyle(LinearProgressViewStyle())
                .padding()
            
            Button("Start") {
                startProgress(progress2: $progress)
            }
            .padding()
        }
    }
    
  
    private func startProgress(progress2: Binding<Double>) {
        DispatchQueue.global().async {
            (0..<100).forEach { index in
                sleep(1)
                DispatchQueue.main.async {
                    progress2.wrappedValue += 0.01
                    print(progress2.wrappedValue)
                }
            }
        }
    }
}

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2