BLACK FRIDAY: Save 50% on all books and bundles! >>

How to show an action sheet

Paul Hudson    @twostraws   

Updated for Xcode 12.0

SwiftUI gives us the ActionSheet view for creating action sheets for the user to choose from, and it works similarly to alerts.

First, you need to define a property that will track whether the action sheet should be visible or not:

@State private var showingSheet = false

Next, here’s the basic code for a SwiftUI action sheet, complete with title, message text, and an array of buttons it should show:

ActionSheet(title: Text("Action"), message: Text("Quote mark"), buttons: [.default(Text("Show Sheet"))])

You can then attach that to your view along with your binding that decides whether it should be visible.

We can put all that together into an example view that triggers the action sheet when a button is tapped:

struct ContentView: View {
    @State private var showingSheet = false

    var body: some View {
        Button(action: {
            self.showingSheet = true
        }) {
            Text("Show Action Sheet")
        .actionSheet(isPresented: $showingSheet) {
            ActionSheet(title: Text("What do you want to do?"), message: Text("There's only one choice..."), buttons: [.default(Text("Dismiss Action Sheet"))])

Save 50% in my Black Friday sale.

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 3.7/5

Link copied to your pasteboard.