在UICollectionView上滚动时,应用程序崩溃

时间:2016-12-25 19:54:43

标签: ios swift

我正在处理一个应用程序,其中一个视图是一个UICollectionView。我已经让集合视图工作得很好。当用户按下其中一个集合视图单元格时,将打开一个带有照片的新视图。但是,当我尝试滚动集合视图时,应用程序崩溃。

这是我的代码:

let cellMapArray = [UIImage(named: "pomona.jpg"), UIImage(named: "Pitzer.jpg"), UIImage(named: "Mudd.jpg"), UIImage(named: "Scripps.jpg"), UIImage(named: "CMC1.jpg")]


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
    return self.schoolNames.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell

    cell.imageView?.image = self.cellMapArray[indexPath.row]

    cell.imageTitle?.text = self.schoolNames[indexPath.row]

    return cell

}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
    self.performSegue(withIdentifier: "showImage", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
    if segue.identifier == "showImage"
    {
        let indexPaths = self.collectionView!.indexPathsForSelectedItems!
        let indexPath = indexPaths[0] as IndexPath
        let vc = segue.destination as! NewViewController
        vc.image = self.mapArray[indexPath.row]!
        vc.title = self.schoolNames[indexPath.row]
    }
}

应用崩溃时突出显示的行是:

 cell.imageView?.image = self.cellMapArray[indexPath.row]

我得到的错误是

  

致命错误:索引超出范围(lldb)。"并且代码行突出显示错误"线程1:EXC_BAD_INSTRUCTION(代码= EXC_l386_INVOP,子代码= 0x0)

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:3)

如错误所述, indexPath.row 值不在数组 cellMapArray 的范围内。确保 cellMapArray 在数组中有足够的元素,以便数组在索引 indexPath.row

中有一个元素
相关问题