2016-08-05 8 views
1

CollectionViewでindexPathForSelectedRowを使用するにはどうすればよいですか?prepareForSegue - CollectionView/TableView

CollectionView /テーブルビュー:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("levelCell", forIndexPath: indexPath) as! CollectionViewCell 

    guard levelListen != nil else { 
     return cell 
    } 

    let levelListe = levelListen[indexPath.row] 
    cell.levelLabel?.text = levelListe.name 

    return cell 
} 

テーブルビュー - prepareForSegue(作品):

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

    if segue.identifier == "zumLevel" { 
     let dstCtl = segue.destinationViewController as! InLevelViewController 

     let indexPath = tableView.indexPathForSelectedRow! 
     dstCtl.levelList = levelListen[indexPath.row] 
    } 
} 

CollectionView - prepareForSegue(動作しない):

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

    if segue.identifier == "zumLevel" { 
     let dstCtl = segue.destinationViewController as! InLevelViewController 

     // like TableView? 
     let indexPath = collectionView.indexPathsForSelectedItems()! 
     dstCtl.levelList = levelListen[indexPath.row] // <--- .row doesn't work, should I use .count ? 
    } 
} 

私は.countを試してみてくださいそれは言う: "予期しないアンラップ中にゼロが見つからない場合 "

+0

うーん:あなたのような何かをしたい場合

はそれが動作するはずです。代わりに、collectionViewとtableViewの両方でdidselectrowatindexpathを試すことができますか?選択に基づいて変数を更新し、performSegueWithIdentifierを呼び出して、新しい更新された変数を新しいViewControllerに渡します。 – KotaBear233

+0

KotaBear233はあなたが望むものを理解しているように見えますが、私はそうではありません。 *なぜ* CollectionViewで 'indexPathForSelectedRow'を使いたいのですか?あなたは何を達成しようとしていますか? 2番目のスニペットは何を達成するのですか?そしてそれはなぜ十分ではありませんか? – Julian

答えて

0

collectionView.indexPathsForSelectedItems()複数のセルを選択できるため、複数のIndexPathを返します。この関数は、IndexPathの配列を返します(例:[NSIndexPath])。

let indexPath = collectionView.indexPathsForSelectedItems() 

if let lastRowSelected = indexPath?.last?.row { 
    dstCtl.levelList = levelListen[lastRowSelected] 
} 
+0

エラー:「オプション値をアンラッピングしている間に予期せずnilが見つかりました」 – Sebastian

+0

'let dstCtl = segue.destinationViewControllerをしようとしてみてください! InLevelViewController'から: 'ガードlet dstCtl = segue.destinationViewController as? InLevelViewController else {assertionFailure( "InLevelViewController型の宛先ではありません")} 'このガードを通過するかどうか不思議です。 – Bacon

+0

はい、それはおそらく私のコードの何か他のものに合格しましたか? – Sebastian

関連する問題