2016-12-11 68 views
0

我試圖創建一個像這樣工作的segue。當我點擊我的第一個視圖控制器中的第一個單元格時,我將轉到第二個視圖控制器並在第二個視圖控制器中顯示我的集合視圖的第一個單元格。當我在第一個視圖控制器中點擊第二個單元格時,我將轉到第二個視圖控制器並在第二個視圖控制器中顯示我的collectionview的第二個單元格。我來了這麼遠,但它不起作用。試圖在2個不同viewController的collectionView單元格之間創建一個segue

FIRST VIEW控制器

var selectedIndexPath: NSIndexPath! 

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 

     selectedIndexPath = indexPath as NSIndexPath 
     performSegue(withIdentifier: "mySegue", sender: self) 
     print (selectedIndexPath) 
    } 

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     if segue.identifier == "mySegue" 
     { 
      let secondVC = segue.destination as! ViewController2 
      secondVC.initialDisplayCellIndexPath = selectedIndexPath 
     } 
    } 

第二視圖控制器

var initialDisplayCellIndexPath: NSIndexPath! 

override func viewWillAppear(_ animated: Bool) { 
     self.collectionView.layoutIfNeeded() 
     self.collectionView.scrollToItem(at: initialDisplayCellIndexPath as IndexPath, at: UICollectionViewScrollPosition.centeredHorizontally, animated: true) 
    } 

enter image description here

當我運行我的應用它,只要我挖掘的一個細胞崩潰。這是錯誤消息:

<NSIndexPath: 0x600000227200> {length = 2, path = 0 - 1} 
fatal error: unexpectedly found nil while unwrapping an Optional value 

和錯誤是在這一行:

self.collectionView.scrollToItem(at: initialDisplayCellIndexPath as IndexPath, at: UICollectionViewScrollPosition.centeredHorizontally, animated: true) 

回答

0

!力展開操作的「崩潰,如果無」經營者的思考和避免它完全直到你真的,真的明白選項。

通過聲明initialDisplayCellIndexPath變量類型爲NSIndexPath!或「隱式解包可選」,您可以保證如果您引用該變量並且它爲零,則您的應用程序將崩潰。而不是這樣做,你應該使用「如果讓」可選鏈或警戒聲明。

如果我們要幫助你弄清楚爲什麼你會崩潰,你需要提供該行的上下文。它有什麼方法?調用堆棧在崩潰時的樣子是什麼?

+0

And is initialDisplayCellIndexPath nil when you crash? –

+0

按照我的建議去做。將initialDisplayCellIndexPath從'NSIndexPath!'類型轉換爲'NSIndexPath?'(從「implicitly unwrapped optional」轉換爲「normal」可選),然後在'viewWillAppear'方法中添加'if let'可選鏈或者一個guard語句來測試nil 。所謂 –

+0

好吧,我改成了這樣'覆蓋FUNC viewWillAppear中(_動畫:BOOL){ 如果initialDisplayCellIndexPath =零{ self.collectionView.layoutIfNeeded() self.collectionView.scrollToItem(在:!initialDisplayCellIndexPath爲IndexPath,在:UICollectionViewScrollPosition.centeredHorizo​​ntal,animated:true) } else { }'現在我的應用程序不會崩潰。當我點擊任何單元格時,第二視圖控制器會出現,但第二視圖控制器中的collectionview不會滾動 –

0

試試這個!將「引用」更改爲您的代碼。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
if let segue = "PHOTOARRAY".cellForItem(at:indexPath) { 
performSegue(withIdentifier: "SEGUENAME", sender:segue) 
}} 

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
if let cell = sender as? UICollectionViewCell { 
if let indexPath = self."FIRSTCOLLECTIONVIEWNAME".indexPath(for:cell) { 
if segue.identifier == "SEGUENAME" { 
let controller : "SECONDCOLLECTIONVIEWCLASSNAME" = segue.destination as! "SECONDCOLLECTIONVIEWCLASSNAME" 
controller."PHOTOARRAY" = self."PHOTOARRAY[indexPath.row] 
} 
} 
} 
} 
相關問題