【发布时间】:2015-11-16 22:27:44
【问题描述】:
我在 Storyboard 中使用了自定义 CollectionViewCell。 当我启动应用程序时,我收到以下消息:
无法将“UICollectionViewCell”类型的值转换为 TestProject.CollectionViewCell。
【问题讨论】:
标签: xcode swift uicollectionview uicollectionviewcell
我在 Storyboard 中使用了自定义 CollectionViewCell。 当我启动应用程序时,我收到以下消息:
无法将“UICollectionViewCell”类型的值转换为 TestProject.CollectionViewCell。
【问题讨论】:
标签: xcode swift uicollectionview uicollectionviewcell
Xcode 中 CollectionViewController 的模板随 viewDidLoad 中的这行代码一起提供,它会更改情节提要中的规范。
// Register cell classes
self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
只需删除该行。
在较旧的 Swift 版本中,该行是:
// Register cell classes
self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
【讨论】:
我遇到了这个问题,因为在viewDidLoad() 我用 UICollectionViewCell 类注册了我的单元格。在我的cellForItemAtIndexPath 中,将 CustomSubcalssCollectionViewCell 用于 dequeueReusableCell。
确保 registerClass 和 dequeueReusableCell 是同一个类解决问题
self.registerClass(SomeUICollectionCellClass.self, forCellWithReuseIdentifier: reuseIdentifier)
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! SomeUICollectionCellClass
【讨论】:
我在单元测试中从 Storyboard 实例化 ViewController 时遇到了这个错误。
storyboard.instantiateViewControllerWithIdentifier("someVC") as! MyViewController
问题是我已将身份检查器中的特定模块分配给情节提要中的该 VC。我删除了它,所以它默认为当前模块,即运行时的应用程序模块和测试时的测试模块。
【讨论】:
self.collectionView!
.register(MyCollectionViewCell.self,
forCellWithReuseIdentifier: reuseIdentifier
)
您不必删除此行。如果您想使用代码注册类,您将注册自己的由UICollectionViewCell.self 继承的单元类
【讨论】:
如果您在 Storyboard 和代码中都注册了您的单元格类,您将收到此错误。选择一个或另一个,永远不要同时选择,问题就会消失。
我希望 Apple 没有在他们的模板中包含这段代码:
self.registerClass(SomeUICollectionCellClass.self, forCellWithReuseIdentifier: reuseIdentifier)
特别是因为他们总是建议您通过 Storyboard 注册您的单元格。让事情变得非常混乱。
【讨论】: