简体   繁体   中英

Swift 2.1 - How to pass index row of collection view cell to another view controller

I'm trying to send indexPath.row of selected cell in collection view to a destination controller (detail view) and I've done the following so far

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 is a type of NSIndexPath so I've tried to convert to Int but I get Cannot assign value of type '(UnsafePointer<Int8>,Int32) -> UnsafeMutablePointer<Int8>' to type 'Int' at runtime

In the destination view controller I've initialized var index = 0 to receive the indexPath.row value

Any idea why I get this error at runtime?

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

You have the following line in didSelectItemAtIndexPath :

var index: Int = indexPath.row

This declares index as being local to this function only. Then in prepareForSegue you have:

detailVC!.index = index

Since you're not getting a compilation error, index must also be defined somewhere else. It's this somewhere else variable that didSelectItemAtIndexPath should be setting. It is probably just

index = indexPath.row

Move the following out of the function and make it a property.

var index: Int = indexPath.row

In prepareForSegue you have the following:

detailVC!.index = index

The variable 'index' isn't declared in the class or locally, so what you get is a function named 'index' which is defined as:

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

If you make 'index' a property, it will be used instead of the function of the same name.

Another solution could be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM