Skip to main content

How to let users pick options from a menu

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to let users pick options from a menu 관련

SwiftUI by Example

Back to Home

How to let users pick options from a menu | SwiftUI by Example

How to let users pick options from a menu

Updated for Xcode 15

Updated in iOS 15

SwiftUI’s Picker view has a dedicated style called .menu that shows a popup menu of its options, with the label for the picker being shown as a tappable button. The menu itself will automatically show a checkmark next to the currently selected option, and can display upwards or downwards depending on the position of the picker on-screen.

To demonstrate this, we could make a small menu button to let the user select a paint color:

struct ContentView: View {
    @State private var selection = "Red"
    let colors = ["Red", "Green", "Blue", "Black", "Tartan"]

    var body: some View {
        VStack {
            Picker("Select a paint color", selection: $selection) {
                ForEach(colors, id: \.self) {
                    Text($0)
                }
            }
            .pickerStyle(.menu)

            Text("Selected color: \(selection)")
        }
    }
}

Download this as an Xcode projectopen in new window

Important

If you’re using Xcode 12, you need to use MenuPickerStyle() rather than .menu.

Similar solutions…
Building a menu using List | SwiftUI by Example

Building a menu using List
How to show a menu when a button is pressed | SwiftUI by Example

How to show a menu when a button is pressed
How to show a context menu | SwiftUI by Example

How to show a context menu
How to let users import videos using PhotosPicker | SwiftUI by Example

How to let users import videos using PhotosPicker
How to let users share content using the system share sheet | SwiftUI by Example

How to let users share content using the system share sheet

이찬희 (MarkiiimarK)
Never Stop Learning.