PrepareForSegue collectionView indexPath using swift
I don't find a good example to do what I want using swift, so I allow myself to ask a question.
Im using collectionView to display PFObjects and I want to send the displayed cell data to a second controller using prepareForSegue.
At this point I am trying to make this piece of code:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "goto_answerquestion"){
var indexpath : NSIndexPath = self.collectionView.indexPathsForSelectedItems()
}
}
this line:
var indexpath : NSIndexPath = self.collectionView.indexPathsForSelectedItems()
raises the following error:
(UICollectionView, numberOfItemsInSection: Int)-> Int does not have a member named 'indexPathsForSelectedItems'
please let me know if I'm using the wrong method, or if you need more data to have an appropriate overview of the problem.
ANSWER
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "segue_identifier"){
// check for / catch all visible cell(s)
for item in self.collectionView!.visibleCells() as [UICollectionViewCell] {
var indexpath : NSIndexPath = self.collectionView.indexPathForCell(item as CollectionViewCell)!
var cell : CollectionViewCell = self.collectionView!.cellForItemAtIndexPath(indexpath) as CollectionViewCell
// Grab related PFObject
var objectData:PFObject = self.questionData.objectAtIndex(indexpath.row) as PFObject
// Pass PFObject to second ViewController
let theDestination = (segue.destinationViewController as answerPageViewController)
theDestination.questionObject = objectData
}
}
}
source to share
If you are just trying to find the path of a cell pointer and not have multiple, you can do this in the prepareForSegue method:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let indexPath = collectionView.indexPathForCell(sender as UICollectionViewCell)
// do what you need now with the indexPath
}
sender
In this situation, you selected a cell, so you just need to cast it to the UICollectionViewCell (or a custom cell subclass if you did).
UPDATE :
Swift 1.2 introduced a as!
replacement as
for this purpose, so for safety reasons, you can try this internally prepareForSegue
using multiple bindings:
if let cell = sender as? UICollectionViewCell, indexPath = collectionView.indexPathForCell(cell) {
// use indexPath
}
source to share