「SwiftUI」ActionSheet/Menu/ContextMenu

Posted by Jiaolong on 2022/04/07

ActionSheet

Example

struct ContentView: View {
    @State private var showActionSheet = false

    var body: some View {
        Button("Eat 🍌") {
            showActionSheet = true
        }
        .actionSheet(isPresented: $showActionSheet) {
            ActionSheet(
                title: Text("Food alert!"),
                message: Text("You have made a selection"),
                buttons: [
                    .cancel(),
                    .destructive(Text("Change to 🍑")) { /* override */ },
                    .default(Text("Confirm")) { /* confirm */ }
                ]
            )
        }
    }
}

A gif displaying a view with a button reading "Eat 🍌", that once pressed triggers the appearance of an action sheet titled "Food alert" with two options, "Change to 🍑" and "Confirm", and a text message beneath the title reading "You have made a selection".

Menu

Example

struct MenuView: View {
    var body: some View {
        Menu {
            Button("Open in Preview", action: { })
            Button("Save as PDF", action: { })
        } label: {
            Image(systemName: "doc")
            Text("PDF")
        }
    }
}

A gif displaying a single button in the center of the screen that reads "Actions" which holds down to present a menu with three different options: Copy, Delete..., or Duplicate. If selected, the Copy button prompts the appearance of a submenu, which has the option to Copy or Copy Formatted.

ContextMenu

Example

func selectHearts() {
    // Act on hearts selection.
}
func selectClubs() { }
func selectSpades() { }
func selectDiamonds() { }

let menuItems = ContextMenu {
    Button("♥️ - Hearts", action: selectHearts)
    Button("♣️ - Clubs", action: selectClubs)
    Button("♠️ - Spades", action: selectSpades)
    Button("♦️ - Diamonds", action: selectDiamonds)
}

struct ContextMenuMenuItems: View {
    private var shouldShowMenu = true
    var body: some View {
        VStack {
            Text("Favorite Card Suit")
                .padding()
                .contextMenu(shouldShowMenu ? menuItems : nil)
        }
    }
}

A gif of a context menu showing four menu items: Hearts, Clubs, Spades and Diamonds.

参考链接: