【问题标题】:How do I segue from a nested collectionView cell?如何从嵌套的 collectionView 单元格中分离?
【发布时间】:2018-02-04 04:28:30
【问题描述】:

我有一个collectionView 用于在页面之间滚动,在这些整页单元格之一中,我还有另一个带有单元格的collectionView。当点击最里面的collectionView中的一个单元格时,如何执行segue。

【问题讨论】:

  • 我的回答有帮助吗?

标签: ios swift uicollectionview segue uistoryboardsegue


【解决方案1】:

您将需要在单元格中的委托,其中包含Collection View,需要在选择特定单元格时通知:

protocol CollectionCellDelegate: class {
    func selectedItem()
}

class CollectionCell: UITableViewCell {

    weak var delegate: CollectionCellDelegate?

    // ...

    func collectionView(_ collectionView: UICollectionView,
                    didSelectItemAt indexPath: IndexPath) {
        self.delegate?.selectedItem()
    }
}

并且在TableViewController 中,您必须实现该委托才能从它执行segue(您必须从UIViewController 子类执行segue,但UITableViewCell 没有对其进行子类化,这就是您需要委托模式的原因)。

class TableViewController: UITableViewController, CollectionCellDelegate {

    // ...

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CollectionCell", for: indexPath) as! CollectionCell
        // set its delegate to self
        cell.delegate = self
        return cell
    }

    func selectedItem() {
        // here you can perform segue
        performSegue(withIdentifier: "mySegue", sender: self)
    }

}

我没有向委托传递任何参数,但您当然可以使用参数来传递 segue 所需的任何信息(例如,选择的集合单元格的 id 等)。

【讨论】:

  • 非常感谢您的回答,它确实有效,真的很有帮助。出于好奇,为什么我们必须为此添加一个委托,以及为什么需要检查collectionView == self.innerCollectionView。效果很好,非常感谢您的详细回答。这很有帮助。
  • @user372382 老实说,我不知道为什么我把支票放在那里 :D .. 我相信你可以删除它,我已经更新了答案
  • 无论如何,非常感谢您的回答,我为此困扰了好几天,感谢您的所有帮助。
【解决方案2】:

当您点击 collectionView 中的项目时,将调用以下委托方法(如果您正确连接所有内容)func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)... 请注意第一个参数是 collectionView 本身。

取决于你如何设置它......

如果您在一个 UIViewController 中有两个 collectionView,那么您可以这样做..

func collectionView(_ collectionView: UICollectionView, 
             didSelectItemAt indexPath: IndexPath) {
  if collectionView == self.innerCollectionView {
     // performSegue...
  }
}

如果您有两个视图控制器,一个用于外部,另一个用于内部..那么您可以创建使用委托模式来让外部知道选择了哪个项目,并使用该信息进行 segue。

【讨论】:

  • 当我尝试在最内部的 collectionView 的 didSelectItemAt 内调用 performSegue 时,我收到错误“使用未解析的标识符 performSegue”
  • 你的视图控制器是如何设置的?
  • 也在故事板中..你是否设置了目标控制器的名称?
  • 我有一个带有UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource 协议和 3 个单元格的 MainViewController,其中每个单元格充当一个视图,然后在这三个页面单元格之一中的一个 collectionViewCell 具有相同的协议,其中包含另一个 collectionView
猜你喜欢
  • 2015-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-08
相关资源
最近更新 更多