Search code examples
iosswiftuitableviewtableviewsegue

Segue not firing from custom tableView cell


I'm experiencing what I'm sure is a beginner's mistake. I have a TableViewController that should segue to a second TableViewController upon selection of a custom cell.

I've segued to a UIViewController from a custom cell in the past but I can't figure out for the life of me why this segue isn't firing. Here's the code for the entire controller that should be firing the segue. Thanks in advance!

import UIKit

class SourcesViewController: UITableViewController {

var sources: [Source] = []

override func viewDidLoad() {
    super.viewDidLoad()
    navigationController?.isNavigationBarHidden = false
    self.navigationItem .setHidesBackButton(true, animated: false)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}




// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return sources.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell_01", for: indexPath) as? SourceCell

        else {
            return tableView.dequeueReusableCell(withIdentifier: "cell_01", for: indexPath)
    }

    let currentSource = sources[indexPath.row]

    cell.sourceLabel.text = currentSource.name

    return cell
}




// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let indexPath = tableView.indexPathForSelectedRow {
        let sourceToSend = sources[indexPath.row]
        if let destination = segue.destination as? ArticlesViewController {
            destination.source = sourceToSend
        }
    }
  }

}

Solution

  • Your segue doesn't get called because you are not invoking it. UIViewController has perfromSegue method that you should use for that purpose.

    From what I see you would want to perform the segue after tapping the cell. To achieve this add UITableViewDelegate method and perform segue from there:

    /// - SeeAlso: UITableViewDelegate
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: "your_identifier_from_the_storyboard", sender: nil)
    }