SwiftUI ActionSheet Tutorial

An action sheet is a specific style of alert that appears in response to a control or action, and presents a set of two or more choices related to the current context. In this tutorial an action sheet is presented containing 3 buttons. SwiftUI requires Xcode 11 and MacOS Catalina, for which the Betas can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the Single View App template, and then click Next. Enter SwiftUIActionSheetTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to

struct ContentView : View {
    // 1.
    @State var showActionSheet: Bool = false
    
    // 2.
    var actionSheet: ActionSheet {
        ActionSheet(title: Text("Action Sheet"), message: Text("Choose Option"), buttons: [
            .default(Text("Save")),
            .default(Text("Delete")),
            .destructive(Text("Cancel"))
        ])
    }

    var body: some View {
        // 3.
        Button(action: {
            self.showActionSheet.toggle()
        }) {
            Text("Display Action Sheet")
        }
        .actionSheet(isPresented: $showActionSheet, content: {
            self.actionSheet })
    }
}
  1. A state property is declared to determine when the action sheet will be displayed.

  2. The actionsheet property is declared. The actionsheet contains two default and one destructive button. When selected the isSheetShowing property is set to false.

  3. A button is displayed. When clicked the action sheet is presented.

Go to the preview pane. Click the live preview button and click on the “display action sheet” button. The action sheet will be presented.

The source code of the SwiftUIActionSheetTutorial can be downloaded at the ioscreator repository on Github.