从 collectionView 到 Detail

From collectionView to Detail

我正在将数据从一个 CollectionViewController 传递到一个细节 ViewController。一切似乎都正常,但 "prepareForSegue 发生在 "didSelectItemAtIndexPath" 之前,所以它传递的是我上次 select 编辑的项目数据,而不是我 select ]现在。

这是我的 collectionViewController

的错误代码
var cellSelected : Int = 0

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    cellSelected = indexPath.row
    println("Did select!")
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "identifierName" {
        var secondScene = segue.destinationViewController as detailVC

        secondScene.authorDetail = data[cellSelected].userOfImg
        secondScene.likesDetail = data[cellSelected].likesInImg
        secondScene.imageDetail = data[cellSelected].imgPath
        println("Prepare for segue")
    }
}

调试区的结果为:

  1. 准备转场
  2. 做了 select!

我找到了解决办法。就是用shouldSelectItemAtIndexPath代替didSelectItemAtIndexPath。这样做 shouldSelectItemAtIndexPath 将在 prepareForSegue 之前执行,并将解决发送您正在选择的项目的数据而不是上次选择的项目的数据的问题。

正解

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "identifierName" {
        var secondScene = segue.destinationViewController as detailVC
        let cell = sender as UICollectionViewCell
        let indexPath = collectionView.indexPathForCell(cell)
        secondScene.authorDetail = data[indexPath.row].userOfImg
        secondScene.likesDetail = data[indexPath.row].likesInImg
        secondScene.imageDetail = data[indexPath.row].imgPath
        println("Prepare for segue")
    }
}