Skip to content

Instantly share code, notes, and snippets.

@miotke
Last active June 23, 2021 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miotke/8065580653980ea8c9ee07026b2a40c5 to your computer and use it in GitHub Desktop.
Save miotke/8065580653980ea8c9ee07026b2a40c5 to your computer and use it in GitHub Desktop.
Shows how to write a basic alert view in SwiftUI with an binding variable to show the alert.
import SwiftUI
// This alert initializer is now deprecated but still works as of writing this
// in iOS 15.
// https://developer.apple.com/documentation/swiftui/alert
struct ContentView: View {
@State private var showAlert = false
var body: some View {
Button("Show alert message") {
showAlert.toggle()
}
.alert(isPresented: $showAlert) {
Alert(title: Text("Here's an Alert Title"), message: Text("Hi, here's an alert message. 👋"), dismissButton: .cancel())
}
}
}
// New alert code as per Apple's documentation.
// As of writing this, the message is not passed into the alert.
// https://developer.apple.com/documentation/swiftui/view/alert(_:ispresented:actions:message:)-8dvt8
@available(iOS 15, *)
struct ContentView: View {
@State private var showAlert = false
let alertTitle = "Alert Title"
var body: some View {
Button("Show alert message") {
showAlert.toggle()
}
.alert(alertTitle, isPresented: $showAlert) {
Button("Hi, Alert button") {
print("Alert button tapped")
}
} message: {
Text("Hlkjlkajsd")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment