调用cellForItemAtIndexPath()时出现EXC_BAD_INSTRUCTION错误

时间:2017-01-02 08:15:41

标签: ios swift

我的代码在获取索引路径中的单元格的行中出现以下错误而崩溃。我在调试时遇到问题。

  

主题:EXC_BAD_INSTRUCTION(代码= EXC_1386_INVOP,子代码= 0x0)

var cell = CollectionViewCell()

for row in 0...self.collectionNetList.count {
   let indexpath = NSIndexPath.init(forRow: row, inSection: 0)

   self.cell = collectionView?.cellForItemAtIndexPath(indexpath) as! CollectionViewCell 

   // ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ CRASHES HERE ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

   cell.dlImage.image=UIImage(named: "ted")  //Modify the custom pictures on the cell
}

然而,在这种方法中,相同的指令按预期工作。

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    self.cell = collectionView.cellForItemAtIndexPath(indexPath)! as! CollectionViewCell
}

2 个答案:

答案 0 :(得分:0)

CollectionViewCell未注册。您需要调用UICollectionView的registerNib方法在viewDidLoad或viewWillAppear方法中注册自定义单元格。

答案 1 :(得分:-1)

if let cell = collectionView.cellForItemAtIndexPath(indexPath) {
    let aCell = cell as! CollectionViewCell
  aCell.dlImage.image=UIImage(named: "ted")
}

这样的权利

相关问题