34

SwiftUI ActionSheet Tutorial

 4 years ago
source link: https://www.tuicool.com/articles/fyAbQre
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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.

z2IBFza.png!web

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

QF3Ibe3.png!web

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

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

    var body: some View {
        // 3
        Button(action: {
            self.isSheetShowing = true
        }) {
            Text("Display Action Sheet")
        }
        .presentation($isSheetShowing) 
    }
}
  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.

26BFfmb.png!web

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK