SwiftUI gives us alert()
for presenting important choices, and sheet()
for presenting whole views on top of the current view, but it also gives us confirmationDialog()
: an alternative to alert()
that lets us add many buttons.
Visually alerts and confirmation dialogs are very different: on iPhones, alerts appear in the center of the screen and must actively be dismissed by choosing a button, whereas confirmation dialogs slide up from the bottom, can contain lots of buttons, and can be dismissed by tapping on Cancel or by tapping outside of the options.
Although they look very different, confirmation dialogs and alerts are created almost identically:
alert()
for alerts and confirmationDialog()
for confirmation dialogs.To demonstrate confirmation dialogs being used, we first need a basic button that toggles some sort of condition:
struct ContentView: View {
@State private var showingConfirmation = false
@State private var backgroundColor = Color.white
var body: some View {
Button("Hello, World!") {
showingConfirmation = true
}
.frame(width: 300, height: 300)
.background(backgroundColor)
}
}
Now for the important part: we need to add another modifier to the button, creating and showing a confirmation dialog when we’re ready.
Just like alert()
, we have a confirmationDialog()
modifier that accepts three parameters: a title, a binding that decides whether the dialog is currently presented or not, and a closure that provides the buttons that should be shown – usually provided as a trailing closure.
We provide our confirmation dialog with a title and optionally also a message, then an array of buttons. These are stacked up vertically on the screen in the order you provide, and it’s generally a good idea to include a cancel button at the end – yes, you can cancel by tapping elsewhere on the screen, but it’s much better to give users the explicit option.
So, add this modifier to your text view:
.confirmationDialog("Change background", isPresented: $showingConfirmation) {
Button("Red") { backgroundColor = .red }
Button("Green") { backgroundColor = .green }
Button("Blue") { backgroundColor = .blue }
Button("Cancel", role: .cancel) { }
} message: {
Text("Select a new color")
}
When you run the app, you should find that tapping the text causes the confirmation dialog to slide over, and tapping its options should cause the text’s background color to change.
SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Link copied to your pasteboard.