2016-12-25 66 views
-1

我正在開發一個應用程序,其中一個視圖是UICollectionView。我已經使集合視圖完全正常工作。當用戶按下其中一個收集視圖單元格時,會打開一個帶有照片的新視圖。但是,當我嘗試在集合視圖上滾動時,應用程序崩潰。在UICollectionView上滾動時應用程序崩潰

這裏是我的代碼:

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

我得到的錯誤是

fatal error: Index out of range (lldb)." And the line of code is highlighted with the error "Thread 1: EXC_BAD_INSTRUCTION (code=EXC_l386_INVOP, subcode=0x0)

任何幫助將是:

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] 
    } 
} 

併線時,應用程序崩潰是高亮不勝感激!

+2

在一個元件中使用多個數組作爲數據源是容易出錯。發生錯誤如果'schoolNames'和'cellMapArray'中的項數不相等。使用自定義類或結構來避免這種錯誤。 – vadian

回答

2

作爲錯誤狀態,則indexPath.row值不是在陣列cellMapArray的邊界。確保cellMapArray具有陣列中的足夠的元素,從而使所述陣列具有索引indexPath.row