Skip to content

Instantly share code, notes, and snippets.

@frankfka
Created July 14, 2020 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save frankfka/704645201f384d93afefc9385b2eed81 to your computer and use it in GitHub Desktop.
Save frankfka/704645201f384d93afefc9385b2eed81 to your computer and use it in GitHub Desktop.
Multi-Segment Picker in SwiftUI
import SwiftUI
import PlaygroundSupport
struct MultiSegmentPickerViewModel {
typealias Label = String
typealias Selection = Binding<Int>
typealias PickerDisplayValues = [String]
let segments: [(Label, Selection, PickerDisplayValues)]
}
struct MultiSegmentPickerView: View {
let viewModel: MultiSegmentPickerViewModel
var body: some View {
GeometryReader { geometry in
HStack {
// Iterate over the individual picker values
ForEach(0..<self.viewModel.segments.count, id: \.self) { pickerIndex in
// Define a picker
Picker(
self.viewModel.segments[pickerIndex].0, // Label
selection: self.viewModel.segments[pickerIndex].1 // Selection
) {
// Populate with data for this specific picker
ForEach(0..<self.viewModel.segments[pickerIndex].2.count) { pickerSelectionIndex in
Text(self.viewModel.segments[pickerIndex].2[pickerSelectionIndex])
// Tag tells SwiftUI which selection to show - we tag with the index
.tag(pickerSelectionIndex)
}
}
.pickerStyle(WheelPickerStyle())
// Size each picker to the allowed fraction of the total width
.frame(width: geometry.size.width / CGFloat(self.viewModel.segments.count))
// Clip to the given width, otherwise the picker lines will overflow & intersect
.clipped()
}
}
}
}
}
let testVm = MultiSegmentPickerViewModel(segments: [
("FirstPicker", .constant(0), ["1.1", "1.2", "1.3"]),
("SecondPicker", .constant(1), ["2.1", "2.2", "2.3"]),
])
PlaygroundPage.current.setLiveView(
MultiSegmentPickerView(viewModel: testVm)
.padding()
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment