Swift3 集合视图 'attempt to delete item 1 from section 1, but there are only 1 sections before the update'

Swift3 collectionView 'attempt to delete item 1 from section 1, but there are only 1 sections before the update'

我的应用因 'attempt to delete item 1 from section 1, but there are only 1 sections before the update'

而崩溃

我发现其他文章说数据源必须与 collectionView 或 tableView 保持同步,所以我从我的数组中删除了对象:在我删除 collectionView 中的项目之前发出警报,这适用于 didSelectItemAtIndexPath。但是我不知道为什么这不起作用。

我也尝试打印 array.count,它显示对象确实从数组中移除。

func disableAlarmAfterReceiving(notification: UILocalNotification) {
    for alarm in alarms {
        if alarm == notification.fireDate {
            if let index = alarms.index(of: alarm) {
                let indexPath = NSIndexPath(item: index, section: 1)

                alarms.remove(at: index)
                collectionView.deleteItems(at: [indexPath as IndexPath])

                reloadCell()
            }
        }
    }
}

func reloadCell() {
    userDefaults.set(alarms, forKey: "alarms")
    DispatchQueue.main.async {
        self.collectionView.reloadData()
        print("Cell reloaded")
        print(self.alarms.count)
    }
}

您只有一个部分,因此您需要将其从 0 部分中删除。也使用 Swift 3 原生 IndexPath directly instead of NSIndexPath.

let indexPath = IndexPath(item: index, section: 0)

alarms.remove(at: index)
DispatchQueue.main.async {
    collectionView.deleteItems(at: [indexPath])
}

编辑: 从 collectionView 中删除项目后尝试打破循环。

if let index = alarms.index(of: alarm) {
    let indexPath = IndexPath(item: index, section: 0)
    alarms.remove(at: index)
    DispatchQueue.main.async {
        collectionView.deleteItems(at: [indexPath])
    }
    reloadCell()

    break
}