UICollectionview cellForItem 返回 nil [英] UICollectionview cellForItem return nil

查看:45
本文介绍了UICollectionview cellForItem 返回 nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

错误:返回 nil

 for index in 0...totalHobbies - 1 {让 indexPath = IndexPath(item: index, section: 1)print(indexPath)//打印 [1, 0]let cell = CollectionInterest.cellForItem(at: indexPath) as!命令集合视图单元格打印(cell.btnInterestToggle.isSelected)如果 cell.btnInterestToggle.isSelected {}}

<块引用>

致命错误:在展开可选值时意外发现 nil

解决方案

在使用可选项时需要非常小心.

如果你强行解开可选值,那么你会在运行时崩溃.因此,在这种情况下,您可以使用 if letguard let.

 for index in 0...totalHobbies - 1 {让 indexPath = IndexPath(item: index, section: 1)if let cell = CollectionInterest.cellForItem(at: indexPath) as?CommandCollectionViewCell {打印(cell.btnInterestToggle.isSelected)如果 cell.btnInterestToggle.isSelected{}} 别的 {打印(无法将集合视图单元格类转换为`CommanCollectionViewCell`")}}

Error: Return nil

for index in 0...totalHobbies - 1 {       
    let indexPath = IndexPath(item: index, section: 1) 
    print(indexPath) // Print [1, 0]
    let cell  = CollectionInterest.cellForItem(at: indexPath) as! CommanCollectionViewCell
    print(cell.btnInterestToggle.isSelected)
    if cell.btnInterestToggle.isSelected {

    }
}

Fatal error: Unexpectedly found nil while unwrapping an Optional value

解决方案

You need to very careful while working with optionals.

If you forcefully unwrap optional value then you get crash at run time. So in that case you can use if let or guard let.

for index in 0...totalHobbies - 1  {

        let indexPath = IndexPath(item: index, section: 1)

        if let cell  = CollectionInterest.cellForItem(at: indexPath) as? CommanCollectionViewCell {

            print(cell.btnInterestToggle.isSelected)
            if cell.btnInterestToggle.isSelected{

            }
        } else {
            print("not able to cast collection view cell class to `CommanCollectionViewCell` ")
        }
    }

这篇关于UICollectionview cellForItem 返回 nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆