Skip to content

Instantly share code, notes, and snippets.

@svenoaks
Last active November 4, 2021 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svenoaks/b02c62c2be5da32daa3d3b53f047a91f to your computer and use it in GitHub Desktop.
Save svenoaks/b02c62c2be5da32daa3d3b53f047a91f to your computer and use it in GitHub Desktop.
struct MultiWheelPicker: UIViewRepresentable {
var selections: Binding<[Double]>
let data: [[Double]]
func makeCoordinator() -> MultiWheelPicker.Coordinator {
Coordinator(self)
}
func makeUIView(context: UIViewRepresentableContext<MultiWheelPicker>) -> UIPickerView {
let picker = UIPickerView()
picker.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
picker.dataSource = context.coordinator
picker.delegate = context.coordinator
return picker
}
func updateUIView(_ view: UIPickerView, context: UIViewRepresentableContext<MultiWheelPicker>) {
for comp in selections.indices {
if let row = data[comp].firstIndex(of: selections.wrappedValue[comp]) {
view.selectRow(row, inComponent: comp, animated: false)
}
}
}
class Coordinator: NSObject, UIPickerViewDataSource, UIPickerViewDelegate {
var parent: MultiWheelPicker
init(_ pickerView: MultiWheelPicker) {
parent = pickerView
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return parent.data.count
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return parent.data[component].count
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 48
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return String(format: "%02.0f", parent.data[component][row])
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
parent.selections.wrappedValue[component] = parent.data[component][row]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment