【问题标题】:Swift3 collectionView 'attempt to delete item 1 from section 1, but there are only 1 sections before the update'Swift3 collectionView '尝试从第 1 节中删除第 1 项,但更新前只有 1 节'
【发布时间】:2017-02-03 10:02:48
【问题描述】:

由于“尝试从第 1 节中删除第 1 项,但更新前只有 1 个节”,我的应用程序崩溃了

我发现其他文章说数据源必须与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)
    }
}

【问题讨论】:

  • let indexPath = NSIndexPath(item: index, section: 1) 更改为let indexPath = NSIndexPath(item: index, section: 0),然后检查。异常本身是非常自我解释的。
  • 从数组中删除对象时尝试调用 reloadData()。

标签: ios swift xcode uilocalnotification collectionview


【解决方案1】:

您只有一个部分,因此您需要将其从 0 部分中删除。也可以直接使用 Swift 3 native IndexPath 而不是 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
}

【讨论】:

  • 我更新了代码,现在它没有崩溃,但单元格也没有删除。
  • @BryceChan 您想从数组 n collectionView 中删除多个项目或单个项目?
  • 我想从 array 和 collectionView 中删除单个项目。
  • @BryceChan 检查我编辑的答案以及这里的reloadCell 是什么?
  • 在编辑中应该是let indexPath = IndexPath(item: index, section: 0)
猜你喜欢
  • 1970-01-01
  • 2020-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多