提问人:Harsh Soni 提问时间:9/28/2023 最后编辑:HangarRashHarsh Soni 更新时间:9/28/2023 访问量:34
致命错误:索引超出范围 。靠近评论
Fatal error: Index out of range . Coming near the comment
问:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell=colView1.dequeueReusableCell(withReuseIdentifier:"cell",for: indexPath) as! MyCollectionViewCell
cell.Image.image=UIImage (named: imagehome[indexPath.row]) //error
if (collectionView==colView2){
let cell = colView2.dequeueReusableCell(withReuseIdentifier:"cell1", for:indexPath) as! CollectionViewCell2
cell.Image1.image = UIImage (named: imageHome2[indexPath.row])
cell.Image1.layer.cornerRadius = cell.frame.height/2
return cell
}
return cell
}
如何解决此错误?
答:
0赞
Duncan C
9/28/2023
#1
重写代码以根据要为其提供单元格的集合视图获取不同的图像:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// Change the line below to dequeue a cell from the collection view passed to the function.
//(Make sure you have a cell with the identifier "cell" defined for both collection views.)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier:"cell",for: indexPath) as! MyCollectionViewCell
if (collectionView==colView2){
let cell = colView2.dequeueReusableCell(withReuseIdentifier:"cell1", for:indexPath) as! CollectionViewCell2
cell.Image1.image = UIImage (named: imageHome2[indexPath.row])
cell.Image1.layer.cornerRadius = cell.frame.height/2
return cell
} else {
// I moved this line into an else block for the other collection view (colView1?)
cell.Image.image=UIImage (named: imagehome[indexPath.row])
// Do the other setup for a cell from colView1 here.
return cell
}
您的代码还尝试从 colView1 中取消单元格的队列,即使请求来自 colView2。那行不通。
评论
if collectionView == colView1 { ... } else if collectionView = colView2 { ... }
colView2
imageHome2
imagehome
tableView(_:numberOfRowsInSection:)
numberOfSections(in:)
imagehome[indexPath.row]