1

I am learning the new Swift programming language and I would like to know how can I pass data from a CollectionViewController to a TableViewController.

My objective is that everytime someone taps one of the cells in the CollectionViewController, this actions takes them to the TableViewController where a list of images related to the selected cell appears.

CollectionViewController.swift

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "listSegue") {
        if let indexPath = self.menuCollection.indexPathsForSelectedItems() {
            let control = (segue.destinationViewController) as TableViewCell
            control.cellImage.image = UIImage(named: sectionImages[indexPath])
}

TableViewCell.swift

class TableViewCell: UITableViewCell {
   @IBOutlet weak var cellImage: UIImageView!
}

TableViewController.swift

Do I have to put some code here??

Please help me I would really appreciate it :) Thank you :)

ketokun
  • 69
  • 1
  • 1
  • 10

2 Answers2

0

It seems highly unlikely that segue.destinationViewController is returning a TableViewCell ;-)

It should be an instance of the UITableViewController-derived class that should be the segue's destination.

I say "UITableViewController-derived" because it needs to be a custom class of your design with public properties you can set -- perhaps with values from the selected cell and/or some other state from your CollectionViewController.

cf

Community
  • 1
  • 1
Bob Mazanec
  • 1,121
  • 10
  • 18
  • Ohhh I understand :) And do you know how could I access my cellImage variable from UITableViewCell? I want to access to that variable in my CollectionViewController – ketokun Nov 05 '14 at 23:18
  • You can't -- it looks like it's specific to your `TableViewCall` class, so that's what you have to put in your `UICollectionView` -- here's a tutorial (though in Objective C): http://skeuo.com/uicollectionview-custom-layout-tutorial – Bob Mazanec Nov 05 '14 at 23:26
0

Firstly, if your data stays in array you need to know the object that you want pass into prepareForSegue. So you may can create a tempVar and assign the value on when it select.

private var testObj: TestObj!
func collectionView(collectionView: UICollectionView, didSelectItemAtPath indexPath: NSIndexPath){testObj = self.testObjects[indexPath.item]}

Secondly, you need crate a public API into TableViewCell, the way you can set the value for it. ie

// MARK: Public API

var objTest: ObjTest!

You may need create segue.identifier to check if you have multiple segue.

if segue.identifier == "Your Segue name" {
        let loginSignupVC = segue.destinationViewController as!
        YourDestination Controller
        //do something here
    }


func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
   object = self.objects[indexPath.item]
    self.performSegueWithIdentifier("Your segue name", sender: self)
}