swiftuitableviewuistoryboardsegue

Swift unable to get to the destination class whenever I select a row in the tableView row


Simple situation. I am getting a crash whenever I select a row in View1.

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let storyboard = UIStoryboard(name: "NextScreen", bundle: nil)
    let controller = storyboard.instantiateViewController(withIdentifier: "NextScreenViewController") as! NextScreenViewController
    self.navigationController?.pushViewController(controller, animated: false)
  }

I do have a NextScreen.xib that is a owner of this class NextScreenViewController Help would be appreciated!


Solution

  • Your code and your description don't match. Your code requires that you have a Storyboard file named "NextScreen", which contains a view controller with the identifier "NextScreenViewController", that is a subclass of UIViewController of type NextScreenViewController.

    Your description says you have a NextScreen.xib that "is a owner of this class NextScreenViewController". Your code isn't trying to load a view controller from an XIB. It is trying to load it from a storyboard. Which is it?

    XIB files and Storyboards are two different ways to include views in your project. If you save your view controller's views in an XIB, you need to load them from an XIB. If you save them in a storyboard, you need to load them fom a storyboard. If you save your view controller's views in an XIB file and then try to load them from a storyboard, your app will crash.

    The crash log you added to your question makes it clear that the storyboard you are trying to load doesn't exist, and that is why you are crashing. It says "Could not find a storyboard named 'PlacesPlusScreen'." That is proof positive.

    Do you have a Storyboard file in your project named "NextScreen", or an XIB file? What line is crashing? What is the exact error message?

    Try changing your function like this:

     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let storyboard = UIStoryboard(name: "NextScreen", bundle: nil)
        guard let controller = storyboard.instantiateViewController(withIdentifier: "NextScreenViewController") as? NextScreenViewController else {
            print("Can't load storyboard with ID 'NextScreenViewController'")
            return
        }
        self.navigationController?.pushViewController(controller, animated: false)
      }
    

    Note that your line

    let storyboard = UIStoryboard(name: "NextScreen", bundle: nil)
    

    Will crash your program and throw an exception with the description "Could not find a storyboard named 'NextScreen' in bundle..." if it can't load your storyboard file.

    So you, again, need to look at the exact crash message in the console, and report it here if you want our help debugging the problem.