【问题标题】:prepareForSegue - CollectionView/TableViewprepareForSegue - CollectionView/TableView
【发布时间】:2016-12-12 08:14:45
【问题描述】:

如何在 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(工作):

    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 时,它说:“在展开可选值时意外发现 nil”

【问题讨论】:

  • 嗯。您可以在 collectionView 和 tableView 上尝试 didselectrowatindexpath 吗?并根据选择更新一个变量,然后调用您的 performSegueWithIdentifier 并将新更新的变量传递给新的 ViewController。
  • KotaBear233 似乎明白你想要什么,但我不明白。 为什么你想在CollectionView中使用indexPathForSelectedRow?你想达到什么目的?第二个sn-p实现了什么,为什么还不够?

标签: ios swift uitableview core-data uicollectionview


【解决方案1】:

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

如果你想做这样的事情,它应该可以工作:

let indexPath = collectionView.indexPathsForSelectedItems()

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

【讨论】:

  • 说错误:“在展开可选值时意外发现 nil”
  • 您可以尝试将let dstCtl = segue.destinationViewController as! InLevelViewController 更改为:guard let dstCtl = segue.destinationViewController as? InLevelViewController else { assertionFailure("destination not of type InLevelViewController") } 我很好奇它是否会通过这个守卫。
  • 在代码中的某处,您在 nil 的变量上使用了 !。当这个错误出现时,你应该看到代码在哪一行停止,你能复制粘贴那行吗?
  • 线路:let indexPath = collectionView.indexPathsForSelectedItems()
  • 你确定你已经去掉了那行的!?
猜你喜欢
  • 1970-01-01
  • 2017-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多