Today, we’ll focus on using the native alert options available in SwiftUI.
SwiftUI provides a straightforward way to display alerts like this:
import SwiftUI
struct ContentView: View {
@State private var showAlert = false // State variable to control alert visibility
var body: some View {
VStack {
Button("Show Alert") {
showAlert.toggle() // Toggle alert visibility
}
.alert(isPresented: $showAlert) { // Present the alert when showAlert is true
Alert(
title: Text("Alert Title"), // Title of the alert
message: Text("This is an alert message."), // Message to display
primaryButton: .default(Text("Confirm")) {
// Action to perform on Confirm
print("Confirmed!")
},
secondaryButton: .cancel() // Action to perform on Cancel
)
}
}
.padding()
}
}
Try implementing native alerts in your app to manage user interactions effectively! The full series is available on my profile and the components can also be found at
Happy Coding! 🎉