【问题标题】:How to send indexpath when performing segue on collectionViewCell?在collectionViewCell上执行segue时如何发送indexpath?
【发布时间】:2017-05-24 11:54:09
【问题描述】:

我有一个包含类似单元格的集合视图控制器,我希望每个单元格都打开具有特定内容的下一个视图控制器。我想我必须将 indexpath.row 与 segue 一起发送,但在这部分我面临一个错误:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let newViewController = segue.destination as?     myCollectionViewController {
        newViewController.passedValue = indexPath.row // exactly here
    }
}

【问题讨论】:

  • myCollectionView.indexPathsForSelectedItems[0]? (或类似的东西)
  • 你不能为你的任务使用这个委托函数 didSelectRowAtIndexPath 吗?

标签: swift uicollectionview segue


【解决方案1】:

您的代码中有几处错误。 indexPath.row 变量未在您的 prepare 函数中声明。要将选定的单元格信息传递给另一个视图控制器,您首先需要在您的类中添加一个全局变量。

var selectedCell = 0

接下来在你的类中实现函数didSelectRowAtIndexPath。每次选择单元格时都会调用此函数。在此函数中获取单元格信息并将其分配给selectedCell var

override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        selectedCell = indexPath.row
    }

现在在您的 prepare 方法中使用这个 var 值并将其传递给下一个控制器

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "YourIdentifier" {
            let VC = segue.destination as! YourViewController 
            VC.passed = selectedCell 
        }
    }

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    在上面的代码中:

        newViewController.passedValue = indexPath.row // exactly here
    

    indexPath 这里的值是多少?是实例变量吗?

    不要使用segue,而是使用UICollectionViewDelegate方法:

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    {
        //Push your controller here
    }
    

    【讨论】:

    • indexPath.row 是 collectionViewCell 的地址。
    • 你写的代码在prepare(for:sender:)方法中。这里没有任何名为 indexPath 的局部变量。这就是我要问的。是实例变量吗?
    猜你喜欢
    • 1970-01-01
    • 2018-12-19
    • 2021-10-11
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多