prepareForSegue collectionView使用swift的indexPath

时间:2014-11-13 00:26:59

标签: swift uistoryboardsegue collectionview

我没有找到任何好的例子来使用swift做我想做的事情,所以我允许自己提出这个问题。

我使用collectionView来显示PFObjects,我想使用prepareForSegue将显示的单元格数据发送到第二个控制器。

此时,我正在努力使代码的这部分工作:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if(segue.identifier == "goto_answerquestion"){
            var indexpath : NSIndexPath = self.collectionView.indexPathsForSelectedItems()
        }
    }

这一行:

var indexpath : NSIndexPath = self.collectionView.indexPathsForSelectedItems()

触发以下错误:

(UICollectionView, numberOfItemsInSection: Int)-> Int does not have a member named 'indexPathsForSelectedItems'

如果我使用了错误的方法,或者您需要其他数据来对问题进行适当的概述,请告诉我。

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
            }
        }
    }

2 个答案:

答案 0 :(得分:10)

如果你只想找到被点击的单元格的索引路径,而不是多个,你可以在prepareForSegue方法中执行此操作:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let indexPath = collectionView.indexPathForCell(sender as UICollectionViewCell)
    // do what you need now with the indexPath
}
在这种情况下,

sender是您点击的单元格,因此您只需将其强制转换为UICollectionViewCell(或自定义单元格子类,如果您创建了一个)。

<强>更新
为此,Swift 1.2引入了as!来替换as,因此为了安全起见,您可以使用多个绑定在prepareForSegue内进行尝试:

if let cell = sender as? UICollectionViewCell, indexPath = collectionView.indexPathForCell(cell) {
    // use indexPath
}

答案 1 :(得分:2)

这可以解决您的问题:

var indexPath : NSArray = self.collectionView.indexPathsForSelectedItems()