Skip to content

Instantly share code, notes, and snippets.

@micheltlutz
Forked from natecook1000/SimplePickerView.swift
Last active October 31, 2017 04:20
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save micheltlutz/e480690f54477312eb757fdd90964a4c to your computer and use it in GitHub Desktop.
Simple UIPickerView subclass upgrade for swift 4
import UIKit
class SimplePickerView : UIPickerView {
class SimplePickerViewModel : NSObject, UIPickerViewDelegate, UIPickerViewDataSource {
var titles: [String]
var selectionHandler: ((_ pickerView: UIPickerView, _ row: Int, _ title: String) -> ())?
init(titles: [String], selectionHandler: ((_ pickerView: UIPickerView, _ row: Int, _ title: String) -> ())? = nil) {
self.titles = titles
self.selectionHandler = selectionHandler
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return titles.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return titles[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectionHandler?(pickerView, row, titles[row])
}
}
let model: SimplePickerViewModel
init(titles: [String], selectionHandler: ((_ pickerView: UIPickerView, _ row: Int, _ title: String) -> ())? = nil) {
self.model = SimplePickerViewModel(titles: titles, selectionHandler: selectionHandler)
print("titles: \(titles)")
super.init(frame: CGRect.zero)
self.delegate = model
self.dataSource = model
}
required init(coder aDecoder: NSCoder) {
self.model = SimplePickerViewModel(titles: [], selectionHandler: nil)
super.init(coder: aDecoder)!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment