Skip to content

Instantly share code, notes, and snippets.

@ihamadfuad
Last active January 24, 2022 07:03
Show Gist options
  • Save ihamadfuad/ca13160b98fc386aa183240ef5fe1295 to your computer and use it in GitHub Desktop.
Save ihamadfuad/ca13160b98fc386aa183240ef5fe1295 to your computer and use it in GitHub Desktop.
SwiftUI: Present Alert From Anywhere Using @Environment
// ºººº----------------------------------------------------------------------ºººº \\
//
// Credit Hamad Fuad.
//
// Author: Hamad Fuad
// Email: ihamadfouad@icloud.com
//
// Created At: 24/01/2022
// Last modified: 24/01/2022
//
// ºººº----------------------------------------------------------------------ºººº \\
import SwiftUI
// Step 1:
/**
1. Create state object in main view:
@StateObject var universalAlert = UniversalAlert()
2. Attach .environment(_ key:...) to main view:
.environment(\.universalAlertKey, universalAlert)
3. Attach alert(...) to main view:
.alert(isPresented: $universalAlert.show) {
universalAlert.alert
}
*/
// Step 2
/**
Usage:
1. Declare in any child view:
@Environment(\.universalAlertKey) var universalAlert
2. Present alert:
universalAlert.alert = Alert(title: Text("Title"),
message: Text("Message"),
primaryButton: .default(Text("Primary"), action: {
}),
secondaryButton: .cancel(Text("Cancel"), action: {
}))
universalAlert.show = true
*/
struct UniversalAlertKey: EnvironmentKey {
static let defaultValue = UniversalAlert()
}
extension EnvironmentValues {
var universalAlertKey: UniversalAlert {
get { return self[UniversalAlertKey.self] }
set { self[UniversalAlertKey.self] = newValue }
}
}
class UniversalAlert: ObservableObject {
@Published var show = false
@Published var alert: Alert!
}
@ihamadfuad
Copy link
Author

I'd love to hear your feedback on this approach.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment