Could not cast value of type ‘UICollectionViewCell’

学习 UICollectionViewController 时,遇到了一个关于’UICollectionViewCell’类型转换的小问题,因为是新手,折腾了好久才搞明白原因。具体表现就是报错 “Could not cast value of type ‘UICollectionViewCell’ to TestProject.CollectionViewCell.”。

参考了网上很多资料,比如设置 Module,检查 DataSource 和 Delegates,最终终于发现了问题的原因。在我自定义的 CustomCollectionViewController 类中的 viewDidLoad() 函数中注册 cell 使用的类名是 UICollectionViewCell,而在 cellForItemAt() 中 dequeueReusableCell() 返回的 cell 类名是 CustomCollectionViewCell,两个 cell 类名不一致,所以会出现类型转换失败的问题。

两处类名保持一致就可避免此问题,正确的做法如下所示:

class CustomCollectionViewController: UICollectionViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Register cell classes
        self.collectionView!.register(CustomCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CustomCollectionViewCell

        // TODO

        return cell
    }

}

参考链接:xcode – Could not cast value of type ‘UICollectionViewCell’ – Stack Overflow

Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google+ photo

You are commenting using your Google+ account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.