Last active
May 10, 2020 18:16
-
-
Save seanli1/51be87d5360da137feb071dc48980679 to your computer and use it in GitHub Desktop.
Clean DoublePicker I made since SwiftUI only offers a single Picker.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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