0

Im making an pickerView with all the month in a year, I would like to create an array with the current month at the beginning of the pickerView and the following month to follow and so on. I already populate the pickerView and the array with all the months and I got the current date too.

let Months = ["January","Febrary","March","April","May","June","July","August","September","October","November","December"]

@IBOutlet var DateLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    DateTime()
}

func DateTime() {

    let time = DateFormatter ()
    let date = DateFormatter ()

    time.timeStyle = .medium
    date.dateStyle = .full

    print(time.string(from: Date()))
    print(date.string(from: Date()))

    //RiderTimeStampRequested = time.string(from: Date())
    DateLabel.text = date.string(from: Date())
}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return Months.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
     return Months[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
     print(Months[row])
}
Jay Patel
  • 2,642
  • 2
  • 18
  • 40
Roger
  • 73
  • 2
  • 12
  • 1
    FYI - don't hardcode your own array of month names. Get them from `DateFormatter monthSymbols` (or one of its variants). – rmaddy Oct 09 '17 at 17:50

1 Answers1

1

If I understood correctly, you want to get an array of all the months after the current month and including the current month. If it is July currently, Your array will contain:

["July", "August", "September", "October", "November", "December"]

To do this, we can use the dropFirst method to drop the first x elements of an array.

You can declare a new property like this:

var monthsInPickerView: [String]!

Then initialise it in viewDidLoad:

let calendar = Calendar.current
let month = calendar.dateComponents([.month], from: Date()).month!
monthsInPickerView = Array(Months.dropFirst(month - 1))

And then you would use monthsInPickerView as the picker view's data source.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • I try to implement what you have here and is giving me this error "Cannot assign value of type 'ArraySlice' to type '[String]!' " in this line monthsInPickerView = Months.dropFirst(month - 1) Thank you – Roger Oct 09 '17 at 18:01
  • it works! thank you very much, one last thing, How do I keep repeating the months ? After December going back to January and so on a constant loop of months. – Roger Oct 09 '17 at 18:46
  • @Roger Something like this might help: https://stackoverflow.com/questions/26063039/uipickerview-loop-the-data Your data source will then be the `monthsInPickerView` array plus all the stuff not in that array. – Sweeper Oct 09 '17 at 18:49