【问题标题】:Swift 2.1 - How to pass index row of collection view cell to another view controllerSwift 2.1 - 如何将集合视图单元格的索引行传递给另一个视图控制器
【发布时间】:2016-03-18 03:55:55
【问题描述】:

我正在尝试将集合视图中选定单元格的 indexPath.row 发送到目标控制器(详细视图),到目前为止我已经完成了以下操作

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    let recipeCell: Recipe!

    recipeCell = recipe[indexPath.row]

    var index: Int = indexPath.row

    performSegueWithIdentifier("RecipeDetailVC", sender: recipeCell)
}


override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "RecipeDetailVC" {

        let detailVC = segue.destinationViewController as? RecipeDetailVC

        if let recipeCell = sender as? Recipe {
            detailVC!.recipe = recipeCell
            detailVC!.index = index
        }
    }
}

indexPath.row 是 NSIndexPath 的一种类型,所以我尝试转换为 Int,但在运行时得到 Cannot assign value of type '(UnsafePointer<Int8>,Int32) -> UnsafeMutablePointer<Int8>' to type 'Int'

在目标视图控制器中我初始化了var index = 0 接收 indexPath.row 值

知道为什么我会在运行时收到此错误吗?

【问题讨论】:

  • 你在哪里得到这个错误?在哪一行?在prepareForSegue 中,您从哪里获得index?它看起来像一个属性变量,但在didSelectItemAtIndexPath 中它是一个局部变量。您的意思是在didSelectItemAtIndexPath 中将 index 属性设置为 indexPath.row

标签: ios swift


【解决方案1】:

将以下内容移出函数并使其成为属性。

var index: Int = indexPath.row

在 prepareForSegue 中,您有以下内容:

detailVC!.index = index

变量'index'没有在类中或本地声明,所以你得到的是一个名为'index'的函数,它定义为:

func index(_: UnsafePointer<Int8>, _: Int32) -> UnsafeMutablePointer<Int8>

如果你将'index'设为一个属性,它将被使用而不是同名的函数。

【讨论】:

    【解决方案2】:

    这是一个 collectionView,所以我相信你应该使用 indexpath.item 而不是 .row

    【讨论】:

    • collectionView 本身可以与 row 一起使用,但 indexpath.item 默认是 Int 类型,所以它对我来说应该是一个更好的选择。我的问题是var index,我应该在全球范围内做到这一点。谢谢。
    【解决方案3】:

    didSelectItemAtIndexPath 中有以下行:

    var index: Int = indexPath.row
    

    这将index 声明为仅对该函数本地。然后在prepareForSegue 你有:

    detailVC!.index = index
    

    由于您没有收到编译错误,index 还必须在其他地方定义。这是didSelectItemAtIndexPath 应该设置的其他变量。可能只是

    index = indexPath.row
    

    【讨论】:

    • 你是对的。我没有全局变量索引,我试图访问这个本地索引,该索引仅适用于 prepareForSegue 内的 didSelectItemAtIndexPath
    【解决方案4】:

    另一种解决方案可能是:

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    
        if segue.identifier == "RecipeDetailVC" {
    
            let detailVC = segue.destinationViewController as? RecipeDetailVC
    
            if let recipeCell = sender as? Recipe {
                detailVC!.recipe = recipeCell
                detailVC!.index = collectionView.indexPathsForSelectedItems()?.first?.item
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多