2017-07-14 14 views
1

我目前有一個UICollectionView表與單元格,我試圖讓每個單元格被創建有自己獨特的視圖控制器。例如,當點擊UICollectionViewCell時,視圖控制器將顯示該特定單元格。我知道我可以創建一個viewcontroller並執行segue只有一個視圖控制器。這隻涵蓋了一個單元格...如果用戶創建了25個單元格......我如何爲每個單元格創建視圖控制器而無需創建一個segue?下面的代碼是創建一個單元格。創建新的視圖控制器UICollectionViewCell點擊

// MARK: Create collection View cell with title, image, and rounded border 

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

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ChatCell 
    let object = objects[indexPath.row] 

    cell.chatLabel.text = object.title ?? "" 
    cell.chatImage.image = object.image 
    if let chatImagePath = object.imagePath { 
     if let imageURL = URL(string: chatImagePath) { 
     cell.chatImage.sd_setImage(with: imageURL) 
     } 
    } 
    cell.layer.borderWidth = 0.5 
    cell.layer.borderColor = UIColor.darkGray.cgColor 
    cell.layer.masksToBounds = true 
    cell.layer.cornerRadius = 8 

    return cell 
} 

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

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 
    let itemWidth = photoCollectionView.bounds.width 
    let itemHeight = photoCollectionView.bounds.height/2 
    return CGSize(width: itemWidth, height: itemHeight) 
} 
+1

但是,您是否真的有這些目標視圖控制器的25個完全不同的設計?或者他們是同一種基本類型的視圖控制器,只是顯示不同的數據? – Rob

+0

@Rob我想爲該單元格創建一個視圖控制器...我不能讓所有的單元格都指向相同的視圖控制器 –

+0

@Rob是他們都有相同的佈局,但我想發佈不同的數據在每個 –

回答

1

在您的問題下方的評論,你澄清,你真的只有你正在過渡到視圖控制器的一個基本類型,但你要確保你提供正確的信息,它的您點擊收集視圖的哪個單元格的基礎。

有兩種基本方法:

  1. 最簡單的,在IB,創建集合觀察室在故事板的一個場景一個SEGUE,然後實現prepare(for:sender:)在始發現場通過任何你需要到下一個場景。

    例如,你可能有一個prepare(for:sender:),做一樣的東西:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
        if let indexPath = collectionView?.indexPathsForSelectedItems?.first, let destination = segue.destination as? DetailsViewController { 
         destination.object = objects[indexPath.item] 
        } 
    } 
    

    現在,這使得一噸的假設(例如,我的收藏視圖有一個數組,objects,我的目標視圖控制器一個DetailsViewController,它有一些object財產,等等),但希望它說明了基本的想法。

  2. 你說你不想使用segue。我不知道爲什麼,但是,如果你真的不想繼續使用,那麼只需使用工具collectionView(_:didSelectItemAt:),然後以編程方式啓動轉換,無論你想要什麼。

+0

這就是我想要做的......我試圖通過單擊單元格來創建一個segue,以顯示該特定單元格的tableviewcontroller ... –

+0

你想看看我的github項目嗎? –

+0

當然,如果它不太毛茸茸。如果有大量不相關的代碼,您可能希望將其縮減爲[最小,完整,可重現的示例](http://stackoverflow.com/help/mcve)。 – Rob

相關問題