Complete the code to create a simple Picker with three options.
struct ContentView: View {
@State private var selection = 0
var body: some View {
Picker("Select a number", selection: $selection) {
Text("One").tag(0)
Text("Two").tag(1)
Text("Three").tag(2)
}.pickerStyle([1]())
}
}The SegmentedPickerStyle shows the picker as horizontal segments, which is a common simple style.
Complete the code to create a DatePicker that shows only the date, not time.
struct ContentView: View {
@State private var selectedDate = Date()
var body: some View {
DatePicker("Select date", selection: $selectedDate, displayedComponents: [1])
}
}Using .date shows only the calendar date picker without time.
Fix the error in the Picker code by completing the missing binding.
struct ContentView: View {
@State private var selectedFruit = "Apple"
let fruits = ["Apple", "Banana", "Cherry"]
var body: some View {
Picker("Select a fruit", selection: [1]) {
ForEach(fruits, id: \.self) { fruit in
Text(fruit).tag(fruit)
}
}
}
}The Picker's selection needs a binding, so use $selectedFruit to pass the binding.
Fill both blanks to create a DatePicker that allows selecting only future dates starting from today.
struct ContentView: View {
@State private var date = Date()
var body: some View {
DatePicker("Pick a date", selection: $date, in: [1]..., displayedComponents: [2])
}
}Using Date()... restricts selection to today and future dates. .date shows only the date picker.
Fill all three blanks to create a Picker that shows a wheel style and updates the selected index.
struct ContentView: View {
@State private var selectedIndex = 0
let colors = ["Red", "Green", "Blue"]
var body: some View {
Picker("Choose color", selection: [1]) {
ForEach(0..<colors.count, id: \.self) { index in
Text(colors[index]).tag([2])
}
}.pickerStyle([3]())
}
}The Picker selection needs a binding $selectedIndex. The tag should be the index. The style is WheelPickerStyle for a spinning wheel.