如何在没有“NSInternalInconsistencyException”错误的情况下在UICollectionView中创建新单元格

时间:2016-07-01 06:41:22

标签: ios swift uicollectionview uicollectionviewcell

如何在没有此错误的情况下创建新单元格

'NSInternalInconsistencyException', reason: 'attempt to insert item 2 into section 0, but there are only 2 items in section 0 after the update'

以下是创建新单元格的代码

@IBAction func SetDate(sender: AnyObject) {

   let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let day = dateTimePicker.date
    let datestring = dateFormatter.stringFromDate(day)
    addDateToArray(datestring)

    let text = textField.text
    addSinceLabelToArray(text!)

    let image = userDefault.objectForKey("image") as! String
    addThemeToImagesArray(image)

    print(dateTimePicker.date)
    print(Globals.datesArray)

    dismissViewControllerAnimated(true, completion: nil)

}

以下是我的应用程序中使用上一代码的日期

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell

    cell.sinceLabel.text = Globals.sinceLabelArray[indexPath.item]
    cell.myBackground.image = UIImage(named: String(Globals.imagesArray[indexPath.item]))

    let day = Globals.datesArray[indexPath.item]
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

    let date1: NSDate = dateFormatter.dateFromString(day)!
        let diffDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Day], fromDate: date1, toDate: date2, options: NSCalendarOptions.init(rawValue: 0))
        cell.dayCountLabel.text = String("\(abs(diffDateComponents.day))")

    cell.backgroundColor = UIColor.blackColor()

    return cell
}

以下是我重新加载数据的方法

func loadList(notification: NSNotification){
    let count = Globals.datesArray.count
    let index = count > 0 ? count - 1 : count
    let indexPath = NSIndexPath(forItem: index, inSection: 0)
    collectionView!.insertItemsAtIndexPaths([indexPath])

}

以下是确定要制作的细胞数量的代码

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return count
}

var count = Globals.datesArray.count as Int

一些额外的细节: (1)SetDate()将字符串保存到结构中的三个静态var数组中。 (2)据我所知,这些数组是空的。

感谢。

1 个答案:

答案 0 :(得分:2)

使用

替换loadList中的代码
collectionView!.reloadData()

或者如果您想将其作为批量更新:

    collectionView.performBatchUpdates({
        self.collectionView!.insertItemsAtIndexPaths([indexPath])
        }, completion: nil)