在CollectionViewCell选择时将信息发送到详细信息视图

时间:2014-12-13 02:13:35

标签: ios swift

我试图将信息发送到有关选择时所选单元格的详细视图。现在,prepareForSegue在集合视图委托方法I之前运行。这导致我发送先前单元格选择的信息而不是当前单元格的信息。

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    collectionView.deselectItemAtIndexPath(indexPath, animated: true)        
    nextScreenRow = indexPath.row

    self.performSegueWithIdentifier("toDetails", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if segue.identifier == "toDetails" {
        let vc = segue.destinationViewController as HistoryDetailsViewController
        vc.postcard = postcards[nextScreenRow]
    }
}

1 个答案:

答案 0 :(得分:1)

两件事。如果segue是从单元格构成的,那么你不应该在代码中调用performSegue;选择单元格将触发没有代码的segue。其次,当你以这种方式连接segue时,你根本不需要实现didSelectItemAtIndexPath(但是如果你只想调用deselectItemAtIndexPath就可以了)。没有必要;你可以在prepareForSegue中做你需要做的一切。该单元格将是发件人,所以可以这样做,

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if segue.identifier == "toDetails" {
        let cell = sender as UICollectionViewCell
        let indexPath = collectionView!.indexPathForCell(cell)
        let vc = segue.destinationViewController as HistoryDetailsViewController
        vc.postcard = postcards[indexPath.item]
    }
}