NEW: Get your ticket for Hacking with Swift Live 2019! >>

< How to add actions to alert buttons   How to push a new view using NavigationButton >

How to show an action sheet

SwiftUI gives us the ActionSheet view for creating action sheets for the user to choose from. However, you do need to make sure you reset your state when it’s dismissed, otherwise you won’t be able to show it again.

I’ll show you all the code in a moment, but I want to break it down first because it’s not easy.

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

@State var showingSheet = false

Next, you should create a property to store your action sheet. This needs title and message text, but should also provide an array of buttons. However – and this is the important part – it should also add a trigger to reset the showingSheet property when the action sheet is dismissed, like this:

var sheet: ActionSheet {
    ActionSheet(title: Text("Action"), message: Text("Quote mark"), buttons: [.default(Text("Show Sheet"), onTrigger: {
        self.showingSheet = false
    })])
}

Once that’s done, you can attach the action sheet to your view using a presentation that either shows the sheet or does nothing based on the value of showingSheet, like this:

.presentation(showingSheet ? sheet : nil)

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

struct ContentView : View {
    @State var showingSheet = false

    var sheet: ActionSheet {
        ActionSheet(title: Text("Action"), message: Text("Quote mark"), buttons: [.default(Text("Woo"), onTrigger: {
            self.showingSheet = false
        })])
    }

    var body: some View {
        Button(action: {
            self.showingSheet = true
        }) {
            Text("Woo")
        }
            .presentation(showingSheet ? sheet : nil)
    }
}

HACKING WITH SWIFT LIVE This July is a new two-day event where you'll be inspired by great speakers on day one then learn all the amazing new features from WWDC on day two – click here for more information and tickets.

< How to add actions to alert buttons   How to push a new view using NavigationButton >
MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>