2016-03-18 74 views
0

我試圖將集合視圖中選定單元格的indexPath.row發送到目標控制器(詳細視圖),我已經完成了以下操作遠Swift 2.1 - 如何將收集視圖單元格的索引行傳遞給另一個視圖控制器

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是,所以我已經試過轉換爲int類型NSIndexPath,但我在運行時

得到Cannot assign value of type '(UnsafePointer<Int8>,Int32) -> UnsafeMutablePointer<Int8>' to type 'Int'在我初始化var index = 0 接收indexPath目標視圖控制器.row值

任何想法,爲什麼我在運行時遇到這個錯誤?

+0

你在哪裏得到這個錯誤?在哪一行?在'prepareForSegue'你從哪裏得到'index'?它看起來像一個屬性變量,但在'didSelectItemAtIndexPath'它是一個局部變量。你的意思是將索引屬性設置爲'didSelectItemAtIndexPath'中的indexPath.row –

回答

1

將以下內容移出該函數並將其設置爲屬性。

var index: Int = indexPath.row 

在prepareForSegue您有以下:

detailVC!.index = index 

變量「指標」類或局部不宣,所以你得到的是一個名爲「索引」功能,它被定義如:

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

如果您將'index'作爲屬性,它將被用來代替相同名稱的函數。

1

這是一個的CollectionView所以我相信你應該使用indexpath.item不.row

+0

collectionView本身與行正常工作,但默認情況下,indexpath.item是一種Int類型,因此對我來說應該是更好的選擇。我的問題是'var index',我應該在全局範圍內完成它。謝謝。 –

1

您有以下行didSelectItemAtIndexPath

var index: Int = indexPath.row 

這聲明index爲本地只此功能。然後在prepareForSegue您有:

detailVC!.index = index 

由於你沒有得到一個編譯錯誤,index也必須在其他地方定義。這是其他地方變量,didSelectItemAtIndexPath應該設置。它可能只是

index = indexPath.row 
+0

你說得對。我沒有一個全局變量索引,我試圖訪問這個局部索引,它只在'prepareForSegue'內有'didSelectItemAtIndexPath'作用域。 –

0

另一種解決辦法是:

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 
     } 
    } 
} 
相關問題