swift2 UICollectionView准备阶段索引单元路径为零iOS 9

hgncfbus  于 2022-11-06  发布在  Swift
关注(0)|答案(3)|浏览(156)

问题是这一行返回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))
}

有什么帮助吗?

osh3o9ms

osh3o9ms1#

问题是如何尝试取回单元格。您必须在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]

        }

    }
}

希望能有所帮助!

ws51t4hk

ws51t4hk2#

尝试这样..

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

kyxcudwk3#

问题是var collectionView在我的ViewController中没有引用,因为这个原因总是返回nil。我的错误,谢谢你的回答。

@IBOutlet weak var collectionView: UICollectionView!

相关问题