繁体   English   中英

如何从嵌套的collectionView单元中查询?

[英]How do I segue from a nested collectionView cell?

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

您将需要一个具有集合视图的单元格的委托,当选择特定的单元格时,将需要通知该委托:

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中点击一个项目时,以下委托方法将被调用(如果您正确地连接了所有东西) func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) ...请注意,第一个参数是collectionView本身。

根据您的设置方式...

如果您在一个UIViewController中具有两个collectionView,则可以这样做。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM