Create a wheel picker using SwiftUI's built-in Picker, to allow the user to select from multiple choices
When you create a form in your application and want to get, let's say, the user's age, you can easily add SwiftUI's built-in number picker.
You can also easily create a segmented picker with SwiftUI's built-in Picker. Let's see how to create a wheel picker, as well as a segmented picker.
Wheel picker
Let's start by creating a wheel picker.
Create a local state where you'll save your number. Initially, we'll set it to 1.
@State private var number: Int = 1
..
Then, simply create your picker. It takes two arguments: the first one is the label you want to give to your Picker, and the second one is the selection - a binding value to the state we just created.
Picker("Your age", selection: $number) {
ForEach(1...100, id: \.self) { number in
Text("\(number)")
}
}
..Inside of the Picker, we'll do a ForEach loop that will loop through the numbers 1 to 100, and display a text with the selected number.
Segmented Picker
Another built-in Picker style is the segmented Picker, like the one in the image below.
Let's create a ProgrammingLanguage enum that we'll be able to iterate over. Each case will be a string, and we'll be able to iterate over them with CaseIterable. Each case can also be identified with its raw value.
enum ProgrammingLanguage: String, CaseIterable, Identifiable {
case swiftui
case react
case flutter
var id: String { self.rawValue }
}
..
Then, create a state for favoriteLanguage. We'll set it to SwiftUI initially.
@State private var favoriteLanguage = ProgrammingLanguage.swiftui
..
Create your Picker. We're iterating over all the cases of the ProgrammingLanguage enum. It's important to add the .tag modifier and add the language as the tag so that it works.
Picker("Programming language", selection: $favoriteLanguage) {
ForEach(ProgrammingLanguage.allCases) { language in
Text(language.rawValue.capitalized)
.tag(language)
}
}
..
To style the Picker as a Segmented Picker, let's add the .pickerStyle modifier and SegmentedPickerStyle as its value.
Picker("Programming language", selection: $favoriteLanguage) {
ForEach(ProgrammingLanguage.allCases) { language in
Text(language.rawValue.capitalized)
.tag(language)
}
}
.pickerStyle(SegmentedPickerStyle())
..
Tags:
* SwiftUI