NEW: Join my free 100 Days of SwiftUI challenge today! >>

How to show an action sheet

Paul Hudson    @twostraws   

Fully updated for Xcode 11.2

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"))])
        }
    }
}

LEARN SWIFTUI FOR FREE I have a massive, free SwiftUI video collection on YouTube teaching you how to build complete apps with SwiftUI – check it out!

Similar solutions…

BUY OUR BOOKS
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.6/5