Skip to content

Instantly share code, notes, and snippets.

@piyushdec
Created August 11, 2025 13:45
Show Gist options
  • Save piyushdec/5df03196ca79561acf977c7ee0e150d8 to your computer and use it in GitHub Desktop.
Save piyushdec/5df03196ca79561acf977c7ee0e150d8 to your computer and use it in GitHub Desktop.
Asyncbutton
import SwiftUI
struct AsyncButton<Label: View>: View {
private let action: () async -> Void
private let label: () -> Label
@State private var isLoading = false
init(
action: @escaping () async -> Void,
@ViewBuilder label: @escaping () -> Label
) {
self.action = action
self.label = label
}
var body: some View {
Button {
runTask()
} label: {
ZStack {
label().opacity(isLoading ? 0 : 1)
if isLoading {
ProgressView()
}
}
}
}
private func runTask() {
isLoading = true
Task {
await action()
isLoading = false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment