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