UICollectionView prepareForSegue indexPathForCell是iOS 9

时间:2016-07-08 01:08:37

标签: ios objective-c swift swift2

问题是此行返回nil:

if let indexPath = self.collectionView?.indexPathForCell(sender as! UICollectionViewCell) 

因此我无法传递任何信息,设置了标识符并设置了委托。

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "DetalleSegueIdentifier" {
        if let indexPath = self.collectionView?.indexPathForCell(sender as! UICollectionViewCell) {
            let detailVC = segue.destinationViewController as! DetalleNoticiaViewController
            detailVC.contact = self.noticia[indexPath.row]
        }
    }
}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    self.performSegueWithIdentifier("DetalleSegueIdentifier", sender: collectionView.cellForItemAtIndexPath(indexPath))
}

任何帮助?

3 个答案:

答案 0 :(得分:1)

问题是如何尝试让细胞恢复原状。您必须在performSegueWithIdentifier中传递单元格,然后在prepareForSegue中恢复它。 这是代码:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    self.performSegueWithIdentifier("DetalleSegueIdentifier", sender: collectionView.cellForItemAtIndexPath(indexPath))
}

然后

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "DetalleSegueIdentifier" {
        if let cell = sender as? UICollectionViewCell{
            let indexPath = self.collectionView!.indexPathForCell(cell)
            let detailVC = segue.destinationViewController as! DetalleNoticiaViewController
            detailVC.contact = self.noticia[indexPath.row]

        }

    }
}

希望它有所帮助!

答案 1 :(得分:1)

尝试这样..

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        self.performSegueWithIdentifier("DetalleSegueIdentifier", sender: indexPath)
    }

并获得这样的索引路径......

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "DetalleSegueIdentifier" {

            let aIndPath = sender as! NSIndexPath

            let detailVC = segue.destinationViewController as! DetalleNoticiaViewController
            detailVC.contact = self.noticia[aIndPath.item]
        }
    }

答案 2 :(得分:0)

问题是我的ViewController中的var collectionView不是引用,因此总是返回nil。我的错误感谢你的答案。

@IBOutlet weak var collectionView: UICollectionView!