UICollectionview cellForItem返回nil

时间:2018-06-15 10:13:49

标签: ios swift uicollectionview

错误:返回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 {

    }
}
  

致命错误:在解包可选值时意外发现nil

1 个答案:

答案 0 :(得分:1)

使用期权时你需要非常小心。

如果你强行打开可选值,那么你会在运行时崩溃。因此,在这种情况下,您可以使用if letguard 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` ")
        }
    }