无法转换类型'UICollectionViewCell'的值

coc*_*oco 55 xcode uicollectionview uicollectionviewcell swift

我在Storyboard中使用自定义CollectionViewCell.当我启动应用程序时,我收到此消息:

无法将"UICollectionViewCell"类型的值转换为TestProject.CollectionViewCell.

coc*_*oco 190

Xcode中CollectionViewController的模板附带了viewDidLoad中的这行代码,它改变了故事板中的规范.

// Register cell classes
self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
Run Code Online (Sandbox Code Playgroud)

只需删除该行.

在较旧的Swift版本中,该行是:

// Register cell classes
self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
Run Code Online (Sandbox Code Playgroud)

  • 一般说明:使用Storyboard原型时没有必要注册单元类.如果您注册,它将取代您的原型. (9认同)

Ste*_*hen 47

我遇到这个问题,因为在viewDidLoad()我用UICollectionViewCell类注册了我的单元格.在我cellForItemAtIndexPath使用的CustomSubcalssCollectionViewCell中用于dequeueReusableCell.

确保registerClassdequeueReusableCell是同一个类解决问题

self.registerClass(SomeUICollectionCellClass.self, forCellWithReuseIdentifier: reuseIdentifier)

let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! SomeUICollectionCellClass
Run Code Online (Sandbox Code Playgroud)


小智 7

当自定义类(在Xcode检查器上)仍然将其类设置为默认的UICollectionViewCell而不是我的TestProject.CollectionViewCell的自定义类时,我收到此错误.

要修复它,只需将自定义类更改为您的实现.

自定义类部分

文件大纲


Seb*_*ian 5

ViewController在单元测试中从情节提要实例化a时遇到了此错误。

storyboard.instantiateViewControllerWithIdentifier("someVC") as! MyViewController
Run Code Online (Sandbox Code Playgroud)

问题是我在身份检查器中为情节提要中的VC分配了一个特定的模块。我删除了它,因此它默认为当前模块,即运行时的应用程序模块和测试时的测试模块。