Pickers in swiftUI are like dropdowns in Android. When picker is used, everything must be placed inside navigation view so that new view can appear for picker values selection.
1 2 3 4 5 |
NavigationView { //All views inside navigation view } |
Picker using String Array.
Pickers are normally put inside the SwiftUI Form view. To fill picker with string array, define string array above body tag. Also an @state variable needs to be defined for saving selected value.
1 2 3 |
//Above body let students = [“Harry”, “Berry”, “Cherry”] @State private var selectedStudent = “Harry” |
Actual picker code is as follows.
1 2 3 4 5 6 |
Picker (“Select your student”, selection: $selectedStudent){ //Variable to store selected student ForEach(students, id: \.self) { //ForEach view to iterate through views Text($0) //Create textview } } |
Dynamic loop Picker
@State variable required for selected value.
1 |
@State private var numberOfPeople = 2 |
Actual Picker code as follows.
1 2 3 4 5 6 |
// Dynamic list Picker(“Number of people”), selection: $numberOfPeople){ ForEach(2..<100){ Text(“\($0) people”) } } |
Segmented Picker
Segmented picker can be created as follows.
1 2 3 4 5 6 7 |
//Segmented Picker Picker(“Tip percentage”, selection: $tipPercentage){ ForEach(tipPercentages, id: \.self){ Text($0, format: .percent) } } .pickerStyle(.segmented) |