Make a segue to a tableview controller from a view controller

Viewed 73

I am trying to make a segue to a table view controller when a button is tapped in my view controller programmatically. Here is my code:

@objc func editProfileButtonAction(sender: UIButton!) {
    print("ButtonTapped")
    
    func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      if let identifier = segue.identifier {
        if identifier == "EditProfile" {
            var editProfileTableViewController = segue.destination as! EditProfileTableViewController
          editProfileTableViewController = self
        }
      }
    }
    
}

I really could use some help. I also need to make a segue to a collection view controller using a button in the same view controller.

2 Answers

Okay to clarify that. There is no way to create a segue programmatically. Segues are the arrows on storyboard linking from one to another VC. They are called with: performSegue. This calls the function prepare.

If you want to show a new VC when hitting a button (without segue), then you use the present(VC(), animated: true, completion: nil) } inside the button function. The VC is presented modally.

@objc func editProfileButtonAction(sender: UIButton!) {
    print("editProfileButtonAction")
    present(EditProfileTableViewController(), animated: true, completion: nil)
}

Make sure, that the segue in the Storyboard has exactly the identifier: "EditProfile". Normally I'm writing identifiers with lower letter in the beginning. You also need to prepare for Segue. For example set the delegate:

  // Set ViewController class as the delegate of the EditProfileTableViewControllerDelegate protocol
  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let identifier = segue.identifier {
      if identifier == "EditProfile" {
        let editProfileTableViewController = segue.destination as! EditProfileTableViewController
        editProfileTableViewController = self
      }
    }
  }

At one point in my coding time, I deleted all my storyboard because of too many error's that I could hardly solve. Now I'm doing it all programmatically. At first it was a bit hard to set up all the view's by myself but after all I'm very glad I'm not using storyboards anymore. For some stuff I need xib's, and for testing storyboard. Just if you're interested: the most iOS programmers are using storyboard, so it's okay if you go on with that. The advantage of doing it all programmatically is that there are no segue's anymore. So just present, and on navigation VC's push, pop, ...

Related