Created
July 30, 2020 05:32
-
-
Save alfian0/432de1f58365dc44ac771fe868159056 to your computer and use it in GitHub Desktop.
This file contains 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 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]) | |
} | |
} |
This file contains 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
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