Search code examples
uicollectionviewxcode7uicollectionviewcellswift2ios9.3

Reload data in a UICollectionView - Swift


I am trying to create a simple calendar using UICollectionView. Everything seems to be working fine. I need to trade the calendar according to months i.e. when I click a button the month should be changed to previous month and the text in all the cells should change according to the previous month. I tried using collectionview!.reloadData() but my app is crashing because of this. I even tried deleting all the cells and then reloading but it docent work either.

Here is my code:

@IBAction func prevMonth(){
    day = -1
    if(month == 1){month = 12
        year = year-1}
    else{
        month = month-1}
    let firstdate = "01-\(month)-\(year)"
    let dcalender = NSCalendar.currentCalendar()
    let formatter:NSDateFormatter = NSDateFormatter()
    formatter.dateFormat = "dd-MM-yyyy"
    let dateComponents = dcalender.components([.Weekday],fromDate: formatter.dateFromString(firstdate)!)
    weekday = dateComponents.weekday
    self.collectionView?.reloadItemsAtIndexPaths((self.collectionView?.indexPathsForVisibleItems())!)
}

My Error:

Invalid update: invalid number of items in section 1.  The number of items contained in an existing section after the update (35) must be equal to the number of items contained in that section before the update (31), plus or minus the number of items inserted or deleted from that section (31 inserted, 31 deleted) and plus or minus the number of items moved into or out of that section (0 moved in, 0 moved out).

I am new to swift and to iOS development so maybe I am missing a very simple point. Please help me out.

UPDATE

I finally understood the reason. It is happening because when I add cells for a particular month, I add them according to the weekdays. So if the 1st day of the month is a Tuesday, I add 2 extra cells at the beginning to skip Sunday and Monday. That is why the number of cells before and after an update is conflicting. What is another way to resolve this?


Solution

  • I finally resolved this question. For anyone who encounters the same issue: Use reloadData() and it will work perfectly fine. My app was crashing because it was running out of indexes in my days array.

    Hope this helps :)