【问题标题】:How to delete sections in collection views如何删除集合视图中的部分
【发布时间】:2024-01-17 20:11:01
【问题描述】:

如何从控制器视图中删除各个部分?我在标题中有一个按钮,一切都已连接。只是不确定如何为 3 个不同的部分编写代码。

我的数据模型

var fire = [UIImages]
var water = [UIImages]
var air = [UIImages]

var fireLabel = [String]
var waterLabel = [String]
var airLabel = [String]

我的单元格配置代码

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

    if indexPath.section == 0 {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! CollectionViewCell

        cell.fire.image = fireImages[indexPath.row]
        cell.fireLabel.text = fireNames[indexPath.row]


    return cell

    } else if indexPath.section == 1 {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! CollectionViewCell

        cell.water.image = waterImages[indexPath.row]
        cell.waterLabel.text = waterNames[indexPath.row]

        return cell

    } else {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! CollectionViewCell

        cell.air.image = airImages[indexPath.row]
        cell.airLabel.text = airNames[indexPath.row]

        return cell

    }

}

这是我的按钮代码,它在每个标题中。我想要做的是,当您单击此按钮时,它会删除整个部分。再次为每个。但我似乎无法让它工作。

//Delete Section Button
@IBAction func deleteSectionButton(sender: UIButton) {

    //Section tag
    let section = sender.tag

    //Update data model
    fireImages.removeAtIndex(section)
    fireNames.removeAtIndex(section)

    self.collectionView?.deleteSections(NSIndexSet(index: section))

}

我收到此错误:

*** 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“无效更新:无效的节数。更新后集合视图中包含的节数 (3) 必须等于更新前集合视图中包含的节数 (3),加上或减去插入或删除的节数(0 插入,1已删除)。'

但我不知道这是什么意思。

【问题讨论】:

  • 您是指选定的行还是整个部分?
  • 一整节.. 很抱歉回复晚了

标签: swift uicollectionview sections


【解决方案1】:

您可以在更新数据后重新加载集合视图。它将按比例将您的数据填充回集合视图

self.collectionView.reloadData();

【讨论】:

  • 问题是更新数据。我有 3 个数组,我不确定这将如何在按钮上工作。
  • 我已经在另一个问题上向您解释了solution。你有时间看吗?