使用Swift准备进行collectionView索引路径的prepareForSegue操作

3
我发现没有合适的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'

如果我使用了错误的方法,或者您需要额外的数据来获得适当的问题概述,请让我知道。

回答

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

1
indexPathsForSelectedItems 返回一个数组,但你把它赋值给了一个 NSIndexPath 类型的变量。 - linimin
你确切想做什么? - Saurabh Prajapati
2个回答

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
}

我原以为单元格会是发送者。谢谢提供信息! - user749127

2
这可能解决你的问题:
var indexPath : NSArray = self.collectionView.indexPathsForSelectedItems()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接