如何从嵌套的collectionView单元格中删除?

时间:2018-02-04 04:28:30

标签: ios swift uicollectionview segue uistoryboardsegue

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

2 个答案:

答案 0 :(得分:2)

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

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等)。

答案 1 :(得分:0)

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

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

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

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

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

相关问题