Skip to content

Instantly share code, notes, and snippets.

@seanli1 seanli1/DoublePicker.swift
Last active May 10, 2020

Embed
What would you like to do?
Clean DoublePicker I made since SwiftUI only offers a single Picker.
import SwiftUI
struct DoublePicker: UIViewRepresentable {
let leftOptions: [Any]
@Binding var leftSelection: Int
let rightOptions: [Any]
@Binding var rightSelection: Int
class Coordinator: NSObject, UIPickerViewDelegate, UIPickerViewDataSource {
let leftOptions: [Any]
let rightOptions: [Any]
let leftSelection: Binding<Int>
let rightSelection: Binding<Int>
init(left leftOptions: [Any], _ leftSelection: Binding<Int>, right rightOptions: [Any], _ rightSelection: Binding<Int>) {
self.leftOptions = leftOptions
self.rightOptions = rightOptions
self.leftSelection = leftSelection
self.rightSelection = rightSelection
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0 {
return String(describing: leftOptions[row])
} else {
return String(describing: rightOptions[row])
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if component == 0 {
leftSelection.wrappedValue = row
} else {
rightSelection.wrappedValue = row
}
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return leftOptions.count
} else {
return rightOptions.count
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
}
func makeCoordinator() -> Coordinator {
Coordinator(left: leftOptions, $leftSelection, right: rightOptions, $rightSelection)
}
func makeUIView(context: Context) -> UIPickerView {
let picker = UIPickerView()
picker.delegate = context.coordinator
picker.dataSource = context.coordinator
return picker
}
func updateUIView(_ uiView: UIPickerView, context: Context) {
uiView.selectRow(leftSelection, inComponent: 0, animated: false)
uiView.selectRow(rightSelection, inComponent: 1, animated: false)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.