2016-08-17 33 views
0

我想使用segue來顯示所選UICollectionViewCell的詳細頁面,但是這個單元位於UITableViewCell中。問題是我不能在TableViewCell中使用「performSegueWithIdentifier」(一個包含CollectionView),我知道這個函數只能用在UIViewController中,但我的數據(來自JSON)在TableViewCell中。我不知道如何從ViewController訪問這些,或者我可以用其他方式來選擇TableViewCell中的CollectionViewCell。這裏是我的代碼:Swift:如何使用Segue選中UICollectionViewCell(在UITableViewCell中)

class TableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate { 

var posts1: [Posts] = [Posts]() 
var posts2: [Posts] = [Posts]() 
var categories: [Category] = [Category]() 
var selectedPost1: Posts? 

我有2門陣列(POST1和posts2),我想SEGUE同時顯示在posts1和posts2陣列的所有項目的細節。

我嘗試添加功能:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 
    self.selectedPost1 = self.posts1[indexPath.row] 


} 

但我內心不能稱之爲 「performSegueWithIdentifier」。有關解決這個問題的任何建議?謝謝。

回答

0

在viewController上使用prepareForSegue,你可以檢查你需要的標識符,然後實例化你想要移動到的正確的視圖控制器。您可以檢查此example

+0

我知道如何使用它的時候它是在一個UITableViewController或UIViewController,但我的單元格在另一個單元格中,我怎麼能在單元格內調用這個函數? –

+0

你必須有一個主要的UITableViewController,你的單元格正確嗎?你從單元格創建一個segue到一個細節視圖?我所建議的是你去你的UITableViewController你重寫prepareForSegue(不performSegueIdentifier)。像這樣的例如 覆蓋FUNC prepareForSegue(賽格瑞:UIStoryboardSegue!發信人:AnyObject){ 如果(segue.identifier == 「加載視圖」){// 數據傳遞到下一個視圖 }} 是 –

+0

,我已經做到了。但我在傳遞數據時遇到了麻煩。我從互聯網上下載了所有數據並將它們存儲在一個數組中,並且該數組位於UICollectionView類(它位於TableView內部)中。我怎樣才能在主UITableViewController中傳遞它們?就像我所有的數據存儲在「posts1」裏面,我怎麼能把它們傳遞給主要的UITableView?謝謝。對不起,我對Swift很陌生。 –

0

你需要在你的UITableViewCell

extension UITableViewCell { 
var parentViewController: UITableViewController? { 
    var parentResponder: UIResponder? = self 
    while parentResponder != nil { 
     parentResponder = parentResponder!.nextResponder() 
     if let viewController = parentResponder as? UITableViewController { 
      return viewController 
     } 
    } 
    return nil 
} 

}

然後didSelectItemAtIndexPath添加擴展

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 
    collectionView.deselectItemAtIndexPath(indexPath, animated: true) 
    if let tableController = parentViewController as? NameOfYourTableViewController { 
     tableController.performSegueWithIdentifier(SegueIdentifier, sender: nil) 
    } 
} 
相關問題