Last active
December 2, 2024 02:28
-
-
Save ihamadfuad/ca13160b98fc386aa183240ef5fe1295 to your computer and use it in GitHub Desktop.
SwiftUI: Present Alert From Anywhere Using @Environment
This file contains 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
// ºººº----------------------------------------------------------------------ºººº \\ | |
// | |
// Credit Hamad Fuad. | |
// | |
// Author: Hamad Fuad | |
// Email: [email protected] | |
// | |
// 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! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'd love to hear your feedback on this approach.