【问题标题】:UICollectionView prepareForSegue indexPathForCell is nil iOS 9UICollectionView prepareForSegue indexPathForCell 为 nil iOS 9
【发布时间】:2016-07-08 01:08:37
【问题描述】:

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

有什么帮助吗?

【问题讨论】:

  • 你的 segue 叫什么名字?按下按钮?在细胞新闻上?
  • 请显示您调用 performSegueWithIdentifier 的代码部分
  • 把你调用 performSegueWithIdentifier 的那部分代码放在哪里

标签: ios objective-c swift swift2


【解决方案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]

        }

    }
}

希望对你有帮助!

【讨论】:

    【解决方案2】:

    像这样尝试..

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

    【讨论】:

      【解决方案3】:

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

      @IBOutlet weak var collectionView: UICollectionView!
      

      【讨论】:

        猜你喜欢
        • 2013-09-15
        • 1970-01-01
        • 1970-01-01
        • 2016-05-11
        • 2020-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多