Updated for Xcode 14.2
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 project
Important: If you’re using Xcode 12, you need to use MenuPickerStyle()
rather than .menu
.
SPONSORED Build a functional Twitter clone using APIs and SwiftUI with Stream's 7-part tutorial series. In just four days, learn how to create your own Twitter using Stream Chat, Algolia, 100ms, Mux, and RevenueCat.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.