Home > OS >  How to perform segue when a cell is selected?
How to perform segue when a cell is selected?

Time:09-17


I am very new to Swift, and i'm wondering how to perform segue when user tap one of the table view cells.

In UITableViewCell controller I tried to type performSegue and wait for hints by Xcode like below

override func setSelected(_ selected: Bool, animated: Bool) {
   if selected {
      performSegue() <- HERE
   }
   super.setSelected(selected, animated: true)
}

I couldn't find any hints, so I think i misunderstand the concept.

Is there any way to perform segue when a cell is tapped? And I also want to send some data to the destination, so it'll be great if you can provide a way to send data to the destination as well.

Thank you in advance.

CodePudding user response:

Segues In Code:

So firstly a good way of performing something when a cell (table view cell) is tapped is using the tableView didSelectRowAt method:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // Place code you want to be performed when a cell is tapped inside of here, for example:
    performSegue(withIdentifier: "identifier", sender Any?) // Make sure your identifier makes sense and is preferably something memorable and easily recognisable.
}
  • The segue identifier is just so that swift/interface builder knows which segue you are referring to.
  • The sender is the thing which caused the segue to be performed an example of this is a UIButton.

Next you will need to prepare for the segue inside of the View Controller which is being segued to using the following method:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Do any required setup for this segue such as passing in data loading required views and specifying how you want the segue to be performed such as if you want the view to be pushed, or presented as a popover etc... for example:
    if let vc = segue.destination as? ViewController { // Downcast to the desired view controller.
    // Configure the view controller here...
    }
}

NOTE: You can also create segues in interface builder by control dragging from something such as a UIButton and then setting the segue identifier in the Attributes Inspector in the panel on the right:

Segues In Interface Builder:

  • Control drag and this menu will pop up for you to select the presentation: Action Segue Screenshot

  • Then set an identifier for the segue in the Attributes panel in the right side of the screen: Segue Attributes Inspector Screenshot

  • Finally prepare for the segue inside of the view controller which will be segued to in code just like you do when creating a segue in code.

This video might also be useful to you to gain more clarification on segues and how to perform and prepare for them etc: https://youtu.be/DxCydBmOqXU

  • Related