Carl Andreas Julsvoll Carl Andreas Julsvoll - 4 months ago 28
iOS Question

Segue programatically from custom tableView inside collectionView

I have two classes:

class FeedAndGroupsViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {}

class eventsCustomCollectionCell: UICollectionViewCell, UITableViewDataSource, UITableViewDelegate {}

... where the collectionView class creates a UITableView.

I am trying to create a custom segue when the tableViewCell is clicked. I have implemented the tableView(didSelectRowAt) function for tableView which works fine. However, I am not able to call performSegue from this function. Anyone know how to solve this?


This is because your class eventsCustomCollectionCell is a UICollectionViewCell subclass not a UIViewController subclass.

func performSegue(withIdentifier identifier: String, sender: Any?)

is a method that is available in UIViewController. So for the solution you can create a protocol in eventsCustomCollectionCell which can have a method

func cellClicked(cell: eventsCustomCollectionCell)

and your FeedAndGroupsViewController can implement this protocol and can call performSegue.

I have written skeleton code for your use case you can refer to this code and get started.

class EventsCustomCollectionCell: UICollectionViewCell,UITableViewDelegate{
    weak var delegate : EventsCustomCollectionCellDelegate?
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        delegate?.didClick(cell: self)

protocol EventsCustomCollectionCellDelegate : class{
    func didClick(cell:EventsCustomCollectionCell)

class FeedAndGroupsViewController: UIViewController,EventsCustomCollectionCellDelegate,UICollectionViewDataSource{
var collectionView : UICollectionView!
var yourArrayForCollectionView = [String]()

func didClick(cell:EventsCustomCollectionCell){
    if let index = collectionView.indexPath(for:cell){
        let object = yourArrayForCollectionView[index.row]
        performSegue(withIdentifier: "Your segue identifier", sender: object)

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Your cell reuse id", for: indexPath) as! EventsCustomCollectionCell
    cell.delegate = self
    return cell

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
    return yourArrayForCollectionView.count

Hope this helps.