Wheel and Segmented Picker in SwiftUI - Overview and Implementation
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)")
}
}
..enum ProgrammingLanguage: String, CaseIterable, Identifiable {
case swiftui
case react
case flutter
var id: String { self.rawValue }
}
@State private var favoriteLanguage = ProgrammingLanguage.swiftui
Picker("Programming language", selection: $favoriteLanguage) {
ForEach(ProgrammingLanguage.allCases) { language in
Text(language.rawValue.capitalized)
.tag(language)
}
}
Picker("Programming language", selection: $favoriteLanguage) {
ForEach(ProgrammingLanguage.allCases) { language in
Text(language.rawValue.capitalized)
.tag(language)
}
}
.pickerStyle(SegmentedPickerStyle())
Comments
Post a Comment