Swift and SwiftUI tutorials for Swift Developers

How to show an Action Sheet in SwiftUI

The SwiftUI framework comes with an ActionSheet view, in iOS 14 or older, to create an action sheet. Basically you can create an action sheet like this:

ActionSheet(title: Text("What do you want to do"), message: nil, buttons: [.default(Text("Delete"))]

You initialize an action sheet with a title and an optional message. The buttons parameter accepts an array of buttons. In the example above it provides a default button called Delete.

To activate an action sheet, you have to attach the actionsheet modifier to a button or a view. If you look inside the SwiftUI documentation, you have two ways to present an action sheet.

You can control the appearance of an action sheet using the isPresented parameter:

func actionSheet(isPresented: Binding, content: () -> ActionSheet) -> some View

Or through an optional binding:

func actionSheet(item: Binding, content: (T) -> ActionSheet) -> some View where T : Identifiable

The action sheets have three types of buttons: default, destructive, and cancel. The default button type is used for common actions. A destructive button is similar to a default button, but with the font color red to indicate destructive actions, such as delete. The cancel button is a special type for dismissing the action sheet.

In the following example:

struct ContentView: View {
    
    @State var isPresented: Bool = false
    
    var body: some View {
        Text("Suscribe to Swift Programming")
            .padding()
        Button("OK") {
            isPresented = true
        }
        .actionSheet(isPresented: $isPresented, content: {
            ActionSheet(title: Text("Learn SwiftUI with Swift Programming"),
                        message: Text("Choose an option:"),
                        buttons: [.default(Text("SwiftUI"),
                                           action: {
                                            print("SwifUI")
                                           }),
                                  .default(Text("Xcode")),
                                  .destructive(Text("SwiftUI, Swift and Xcode"))])
        })
    }
}

The result in XCode is as follows:

The ActionSheet component allows you to create a system-native choice selection view. It is typically used to notify the user about something happening in the application or when they need to make an accept or cancel decision. It is an equivalent component to UIAlertController of type .actionSheet in UIKit.

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Article

Swipe to Delete in SwiftUI

Next Article

How to show multiple options with ConfirmationDialog() in SwiftUI

Related Posts