Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 如何在IndexPath 0处添加按钮/默认UICollectionViewCell而不获取;致命错误:索引超出范围“;_Swift_Uicollectionview_Uicollectionviewcell - Fatal编程技术网

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

Swift 如何在IndexPath 0处添加按钮/默认UICollectionViewCell而不获取;致命错误:索引超出范围“;,swift,uicollectionview,uicollectionviewcell,Swift,Uicollectionview,Uicollectionviewcell,我正在尝试添加一个默认单元格,用作我的cellForItemAt方法中的“添加新”按钮,同时仍在我的集合视图中返回正确的项数,但是,我尝试的方法要么返回错误的项数,要么导致崩溃索引超出范围 我正在努力做到这一点 这是我的numberOfItemsInSection方法 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { i

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

我正在努力做到这一点

这是我的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项的情况下执行此操作,非常感谢任何帮助。

当您应该减去时,您正在添加

替换此行:

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

因为当
indexPath.row
1
时,您需要数组中的第一项(即索引
0
处的项)


此外,您还可以通过观察
newsArticles.count
0
,然后
newsArticles.count+1
将是
1
,这样就没有理由对其进行特殊处理

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

    return 0
}
注意:使用
==
而不是
=
检查这两个项目是否引用了同一个对象

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

    return 0
}