İçeriğe geç

SwiftUI ile AsyncButton oluşturmak

Merhabalar, Bu yazımda SwiftUI ile custom bir Async button oluşturarak kullanımını sizlerle paylaşacağım.

Swift 5.5 ile aramıza katılan Async/await ile birlikte içe içe geçmiş closure kullanmadan safe thread yönetimi ile işlemleri yürütebileceğimiz yapı dile eklenmişti. Bu yapıyı custom bir SwiftUI button nesnesine implement ederek Async fonksiyonlarınızı çağırabilirsiniz.

struct AsyncButton<Label: View>: View {
    
    var action: () async -> Void
    @ViewBuilder var label: () -> Label
    @State private var isPerformingTask = false
    
    var body: some View {
        Button(
            action: {
                isPerformingTask = true
                
                Task {
                    await action()
                    isPerformingTask = false
                }
            },
            label: {
                ZStack {
                    label().opacity(isPerformingTask ? 0 : 1)
                    if isPerformingTask { ProgressView().progressViewStyle(CircularProgressViewStyle(tint: .white)).zIndex(1) }
                }
            }
        )
            .disabled(isPerformingTask)
    }
}
struct ContentView: View {
    var body: some View {
        VStack {
            AsyncButton {
                await actionOne()
                await actionSecond()
                print("Completed!")
            } label: {
                Text("Continue")
            }
            .foregroundColor(.white)
            .padding()
            .background(Color.orange)
            .cornerRadius(14)
        }
    }
    
    func actionOne() async {
        (0...3).forEach { i in
            print("Hello", i)
        }
    }
    
    func actionSecond() async {
        (4...7).forEach { i in
            print("World", i)
        }
    }
}
Kategori:SwiftUI

İlk Yorumu Siz Yapın

Bir cevap yazın

E-posta hesabınız yayımlanmayacak.

Copyright © 2022 Kenan Atmaca