Skip to content

Instantly share code, notes, and snippets.

@alfian0
Created July 30, 2020 05:32
Show Gist options
  • Save alfian0/432de1f58365dc44ac771fe868159056 to your computer and use it in GitHub Desktop.
Save alfian0/432de1f58365dc44ac771fe868159056 to your computer and use it in GitHub Desktop.
import UIKit
class GenericPickerView<T>: UIPickerView, UIPickerViewDataSource, UIPickerViewDelegate {
var items: [T] = [] {
didSet {
reloadAllComponents()
}
}
var titleForRow: ((T) -> String?)?
var selectionHandler: ((T) -> Void)?
init(items: [T], titleForRow: ((T) -> String?)?, selectionHandler: ((T) -> Void)?) {
super.init(frame: .zero)
self.items = items
self.titleForRow = titleForRow
self.selectionHandler = selectionHandler
self.delegate = self
self.dataSource = self
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
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 titleForRow?(items[row])
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectionHandler?(items[row])
}
}
let picker = GenericPickerView<String>(items: ["Satu", "Dua"], titleForRow: { (title) -> String? in
return title
}) { [weak self] (title) in
self?.tries.text = title
}
tries.inputView = picker
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment