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
}
如何解决这个错误?
重写代码以获取不同的图像,具体取决于您为其提供单元格的集合视图:
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
}
即使请求来自 colView2,您的代码也会尝试将单元格从 colView1 中出列。那是行不通的。