prepareForSegue - CollectionView / TableView

时间:2016-08-05 20:23:54

标签: ios swift uitableview core-data uicollectionview

如何在CollectionView中使用 indexPathForSelectedRow

的CollectionView / TableView中:

    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
}

TableView - prepareForSegue(work):

    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 时,它说:&#34; 意外地在展开可选值时发现了nil &#34;

1 个答案:

答案 0 :(得分:0)

collectionView.indexPathsForSelectedItems()返回多个IndexPath,因为您可以选择多个单元格。此函数返回一个IndexPaths数组,例如[NSIndexPath]。

如果您执行以下操作,它应该可以工作:

let indexPath = collectionView.indexPathsForSelectedItems()

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