如何在IndexPath 0处添加按钮/默认UICollectionViewCell而不出现“致命错误:索引超出范围”

时间:2018-06-29 01:42:22

标签: swift uicollectionview uicollectionviewcell

我正在尝试在cellForItemAt方法中添加一个默认单元格以用作“添加新”按钮,同时仍在集合视图中返回正确数量的项目,但是,我尝试过的方法都返回了错误的数字项或导致崩溃索引超出范围

我正在努力实现这一目标。

enter image description here

这是我的numberOfItemsInSection方法。

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if collectionView == newsCollectionView {
        if newsArticles.count > 0 {
            return newsArticles.count + 1
        } else if newsArticles.count == 0 {
            return 1
        }
    }

    return 0
}

这是我的cellForItemAt方法

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if collectionView == newsCollectionView {
        if indexPath.row == 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "newsDefaultCell", for: indexPath) as UICollectionViewCell

            return cell
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "newsArticleCell", for: indexPath) as! newsArticleCell

            cell.news = newsArticles[indexPath.row + 1]

            return cell
        }
    }

    return UICollectionViewCell()
}

我知道这行导致崩溃

return newsArticles.count + 1

我只是在寻找一种替代方法,不会比我少退回1件商品,我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

您应该加减。

替换此行:

cell.news = newsArticles[indexPath.row + 1]

具有:

cell.news = newsArticles[indexPath.row - 1]

由于indexPath.row1时,您需要数组中的第一项(即索引为0的项)。


此外,您可以通过观察numberOfItemsInSectionnewsArticles.count来简化0,那么newsArticles.count + 1将为1,因此没有必要特别说明装上它。

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if collectionView === newsCollectionView {
        return newsArticles.count + 1
    }

    return 0
}

注意:使用===而不是==来检查这两项是对同一对象的引用。