Created
August 28, 2019 22:24
-
-
Save jakehawken/92c016216d851ba3dd4d6b2af4a0bae3 to your computer and use it in GitHub Desktop.
Simple, genericized Swift object for backing UIPickerViews. All you need is an array and a callback block and you're golden.
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
| // PickerHandler.swift | |
| // Created by Jake Hawken on 8/27/19. | |
| import Foundation | |
| import UIKit | |
| class PickerHandler<T: CustomStringConvertible> { | |
| typealias ItemSelectionCallback = (T)->() | |
| private let implementation: PickerHandlerImplementation<T> | |
| init(items: [T], selectionCallback: ItemSelectionCallback?) { | |
| implementation = PickerHandlerImplementation(items: items, selectionCallback: selectionCallback) | |
| } | |
| func becomeHandlerFor(picker: UIPickerView) { | |
| picker.dataSource = implementation | |
| picker.delegate = implementation | |
| } | |
| } | |
| private class PickerHandlerImplementation<T: CustomStringConvertible>: NSObject, UIPickerViewDataSource, UIPickerViewDelegate { | |
| private let items: [T] | |
| private let itemSelectionCallback: PickerHandler<T>.ItemSelectionCallback? | |
| init(items: [T], selectionCallback: PickerHandler<T>.ItemSelectionCallback?) { | |
| self.items = items | |
| self.itemSelectionCallback = selectionCallback | |
| super.init() | |
| } | |
| func numberOfComponents(in pickerView: UIPickerView) -> Int { | |
| return 1 | |
| } | |
| func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { | |
| return items.count | |
| } | |
| func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { | |
| return items[row].description | |
| } | |
| func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { | |
| let item = items[row] | |
| itemSelectionCallback?(item) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment