collectionView.cellForItem崩溃

时间:2017-08-17 11:14:52

标签: swift uicollectionview

我在funciton调用中使用了collectionView.cellForItem:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let cell = collectionView.cellForItem(at: indexPath) as! PlaybookPlayCell
    ......
    ......
}

工作正常。这告诉我集合视图设置正确完成。 但是,如果我使用collectionView.cellForItem(at:indexPath)函数调用sizeForItemAt我的单元格分配崩溃

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let cell = collectionView.cellForItem(at: indexPath) as! PlaybookPlayCell // CRASH ON THIS LINE

    ...
    ...

    return CGSize(width: ...., height: ......)
}    

获得一些输入会很棒。 感谢

2 个答案:

答案 0 :(得分:1)

它总是为零,因为在初始化集合视图(collectionView.cellForItem(at: indexPath))之前将调用collectionView.cellForRaw(at: indexPath)。在两个中设置断点,你会看到。

答案 1 :(得分:0)

对于初学者来说,永远不要强制打开选项,否则你的应用程序可能会意外崩溃。

替换

let cell = collectionView.cellForItem(at: indexPath) as! PlaybookPlayCell // CRASH ON THIS LINE

使用:

guard let cell = collectionView.cellForItem(at: indexPath) as? PlaybookPlayCell else {
    // This wasn't expected
    // return something
}

然后在'else'子句中添加一些东西来帮助您调试问题。例如

let unexpected = collectionView.cellForItem(at: indexPath)

走上一条线,看看'意外'。它没有?它是一种不同的类型吗?这可以让你进一步解决你的问题。