I'm setting up a new project with a UICollectionView
that displays an image. I created the ViewController
and the CellViewController
, just like its supposed to.
我正在设置一个带有显示图像的UICollectionView的新项目。我创建了ViewController和CellViewController,就像它应该的那样。
In the CellViewController
the code is the following:
在CellViewController中,代码如下:
import UIKit
class ClubCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
}
But in the ViewController
when I'm setting up the image it gives me the error. Here's the code:
但是在ViewController中,当我设置图像时,它给了我错误。这是代码:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,
for: indexPath)
// Configure the cell
cell.backgroundColor = UIColor.black
cell.imageView.image = UIImage(named: "pic1")
return cell;
}
Thanks in advance..
提前致谢..
1 个解决方案
#1
1
You should cast your collectionViewCell subclass as your custom one ClubCollectionViewCell
.
您应该将collectionViewCell子类强制转换为自定义的ClubCollectionViewCell。
Use guard
to check for the type of the cell, do fatalError()
if it fails.
使用guard检查单元格的类型,如果失败则执行fatalError()。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,
for: indexPath) as? ClubCollectionViewCell else {
fatalError("Wrong cell class dequeued")
}
// Configure the cell
cell.backgroundColor = UIColor.black
cell.imageView.image = UIImage(named: "pic1")
return cell
}
#1
1
You should cast your collectionViewCell subclass as your custom one ClubCollectionViewCell
.
您应该将collectionViewCell子类强制转换为自定义的ClubCollectionViewCell。
Use guard
to check for the type of the cell, do fatalError()
if it fails.
使用guard检查单元格的类型,如果失败则执行fatalError()。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,
for: indexPath) as? ClubCollectionViewCell else {
fatalError("Wrong cell class dequeued")
}
// Configure the cell
cell.backgroundColor = UIColor.black
cell.imageView.image = UIImage(named: "pic1")
return cell
}