Skip to content

Instantly share code, notes, and snippets.

@dilipiOSDeveloper
Created August 27, 2018 10:10
Show Gist options
  • Save dilipiOSDeveloper/ef86d5dc1c2a595f6aed4aeb766e77b7 to your computer and use it in GitHub Desktop.
Save dilipiOSDeveloper/ef86d5dc1c2a595f6aed4aeb766e77b7 to your computer and use it in GitHub Desktop.
// MonthYearPicker.swift
import UIKit
class MonthYearPickerView: UIPickerView, UIPickerViewDelegate, UIPickerViewDataSource {
var months: [String]!
var years: [Int]!
var month = Calendar.current.component(.month, from: Date()) {
didSet {
selectRow(month-1, inComponent: 0, animated: false)
}
}
var year = Calendar.current.component(.year, from: Date()) {
didSet {
selectRow(years.index(of: year)!, inComponent: 1, animated: true)
}
}
var onDateSelected: ((_ month: Int, _ year: Int) -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
self.commonSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonSetup()
}
func commonSetup() {
// population years
var years: [Int] = []
if years.count == 0 {
var year = NSCalendar(identifier: NSCalendar.Identifier.gregorian)!.component(.year, from: NSDate() as Date)
for _ in 1...15 {
years.append(year)
year += 1
}
}
self.years = years
// population months with localized names
var months: [String] = []
var month = 0
for _ in 1...12 {
months.append(DateFormatter().monthSymbols[month].capitalized)
month += 1
}
self.months = months
self.delegate = self
self.dataSource = self
// let previousMonthDate = Calendar.current.date(byAdding: .month, value: -1, to: Date())
// let calendar = NSCalendar.current
// let year = calendar.component(.year, from: previousMonthDate!)
// let month = calendar.component(.month, from: previousMonthDate!)
let currentMonth = NSCalendar(identifier: NSCalendar.Identifier.gregorian)!.component(.month, from: NSDate() as Date)
self.selectRow(currentMonth - 1, inComponent: 0, animated: false)
}
// Mark: UIPicker Delegate / Data Source
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
switch component {
case 0:
return months[row]
case 1:
return "\(years[row])"
default:
return nil
}
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch component {
case 0:
return months.count
case 1:
return years.count
default:
return 0
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let month = self.selectedRow(inComponent: 0)+1
let year = years[self.selectedRow(inComponent: 1)]
if let block = onDateSelected {
block(month, year)
}
self.month = month
self.year = year
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment