2016-02-10 73 views
0

你好我在我的控制器中實現了一個UICollectionView。我在每個單元上顯示了很多信息。當用戶單擊特定的單元格時,我想將單元格中的所有信息傳遞給另一個控制器。如何從被點擊的單元格中獲取信息collectionview

因爲我在數據庫中顯示數據庫中的所有數據,並且單元格正在動態生成,因此我認爲一種方法可能是將一個單元格中的記錄標識傳遞給此函數didSelectItemAtIndexPath,然後在第二個控制器中再次查詢來自數據庫。但我認爲這不是好主意。並且我也不知道如何在這個函數didSelectItemAtIndexPath中傳遞id或任何信息。

因此,在短期我想顯示在正在顯示在其中被點擊

在這裏,小區的其他控制器所有的信息是我的代碼

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath 
     indexPath: NSIndexPath) -> UICollectionViewCell { 

      let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", 
       forIndexPath: indexPath) as! CardsCollectionCell 
      cell.usernameLabel.text = (((dict["\(indexPath.item)"] as?NSDictionary)!["Trip"] as?NSDictionary)!["userName"] as?NSString)! as String 
      cell.feeLabel.text = (((dict["\(indexPath.item)"] as?NSDictionary)!["Trip"] as?NSDictionary)!["fee"] as?NSString)! as String 

      return cell 
    } 

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 

     } 
+1

嘿,我建議你創建一個模型類來在不同視圖之間共享數據。它會比傳遞選擇的全部信息更容易 –

回答

1

因此,讓我們去通過部分解釋,該didSelectItemAtIndexPath委託方法來知道什麼UICollectionViewCellUICollectionViewController被竊聽,你可以得到UICollectionViewCell很容易使用的方法cellForItemAtIndexPath(這是不一樣的collectionView(collectionView: UICollectionView, cellForItemAtIndexPath)像下面的代碼:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 
    let cell = self.collectionView?.cellForItemAtIndexPath(indexPath) as! CardsCollectionCell 
    // access to any property inside the cell you have. 
    // cell.usernameLabel.text 
} 

所以關於總之我要顯示在正在顯示在其中被點擊

可以使用didSelectItemAtIndexPath方法沒有任何問題,以啓動該小區的其他控制器的所有信息使用方法performSegueWithIdentifier到另一個UIViewController的手動輪詢,並且只在prepareForSegue中傳遞您需要傳遞給另一個UIViewController的任何數據。看到下面的代碼:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    // the identifier of the segue is the same you set in the Attributes Inspector 
    self.performSegueWithIdentifier("segueName", sender: self) 
} 

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 

    if(segue.identifier == "segueName") { 
     // this is the way of get the indexPath for the selected cell 
     let indexPath = self.collectionView.indexPathForSelectedRow() 
     let row = indexPath.row 

     // get a reference to the next UIViewController 
     let nextVC = segue.destinationViewController as! NameOfYourViewController 
    } 
} 

我希望這可以幫助你。

+0

感謝您的回答。好吧,我現在瞭解這個概念。現在我的第二個問題是好的我在這裏得到索引路徑let indexPath = self.collectionView.indexPathForSelectedRow()..讓我說我已經在任何單元格中顯示用戶名。我怎麼能在這個單元格的prepareforsegue中獲得用戶名呢? – hellosheikh

+0

你需要從你有'UICollectionView'填充的地方獲得一些dataSource,你有'indexPath.row',這樣你就有了dataSource的索引。 –

+0

對不起,不太瞭解。是的,我認爲我有數據源。好吧,你在代碼中看到我如何獲取數據並顯示它。通過看到它如何獲得用戶名或任何變量在這裏indexpath.row? – hellosheikh

相關問題