-
-
Save gondo/4fbd565fc6b42545e5a0c9f06894ca9d to your computer and use it in GitHub Desktop.
SwiftUI view modifier for presenting an alert when an error binding has a value.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
public extension View { | |
func alert<Message: View, Actions: View>( | |
_ title: LocalizedStringResource, | |
presenting error: Binding<Error?>, | |
@ViewBuilder message: @escaping (Error) -> Message, | |
@ViewBuilder actions: @escaping () -> Actions | |
) -> some View { | |
modifier( | |
ErrorAlertViewModifier( | |
title: title, | |
error: error, | |
actions: actions, | |
message: message | |
) | |
) | |
} | |
func alert<Message: View>( | |
_ title: LocalizedStringResource, | |
presenting error: Binding<Error?>, | |
@ViewBuilder message: @escaping (Error) -> Message | |
) -> some View { | |
modifier( | |
ErrorAlertViewModifier(title: title, error: error) { | |
Button(role: .cancel) { | |
error.wrappedValue = nil | |
} label: { | |
Text("OK") | |
} | |
} message: { error in | |
message(error) | |
} | |
) | |
} | |
} | |
private struct ErrorAlertViewModifier<Message: View, Actions: View>: ViewModifier { | |
let title: LocalizedStringResource | |
@Binding var error: Error? | |
@ViewBuilder let actions: () -> Actions | |
@ViewBuilder let message: (Error) -> Message | |
@State private var isAlertPresented = false | |
private var hasError: Bool { | |
error != nil | |
} | |
func body(content: Content) -> some View { | |
content | |
.alert(title, isPresented: $isAlertPresented) { | |
actions() | |
} message: { | |
if let error { | |
message(error) | |
} | |
} | |
.onChange(of: hasError) { _, newValue in | |
isAlertPresented = newValue | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment