我将数据从一个CollectionViewController
传递到详细信息ViewController
。一切似乎都在起作用,但是"prepareForSegue
发生在"didSelectItemAtIndexPath"
之前,所以它传递的是我最后一次选择的项目的数据而不是我现在正在选择的项目。
这是我对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")
}
}
调试区域的结果是:
答案 0 :(得分:3)
我找到了解决方法。要使用shouldSelectItemAtIndexPath
代替didSelectItemAtIndexPath
。执行此操作shouldSelectItemAtIndexPath
将在prepareForSegue
之前执行,并将解决发送您正在选择的项目的数据的问题,而不是上次选择的项目。
答案 1 :(得分:1)
正确的解决方案
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")
}
}