ray john
ray john

Reputation: 261

Trigger segue from UITableView without Controller

I have a UITableView class that I have placed in multiple ViewControllers.

I would like to segue to another ViewController when the user didSelectRowAtIndexPath.

However, because the UITableView class is standalone, I am not able to trigger segues programmatically from the class, because the self in self.performSegueWithIdentifier or in self.showViewController refers to a UITableView.

I understand that it is the ViewControllers that should be responsible for segues, but I cannot access the didSelectRowAtIndexPath from the given ViewController (because it does not manage the UITableView).

How do I segue from a UITableView that does not inherit from a ViewController?

Upvotes: 1

Views: 96

Answers (2)

Mike Taverne
Mike Taverne

Reputation: 9352

You need a way to tell the view controller that a row on the table view has been selected, so that the view controller can perform the segue.

A delegate is a good way to enable this communication.

  1. Define a delegate protocol.

     protocol TableRowSelectionDelegate: class {
         func tableRowSelected(rowValue: String)
     }
    
  2. Define a delegate variable in your table view class.

    var tableRowSelectionDelegate: TableRowSelectionDelegate?
    
  3. In your table view class, when the table row is selected, call the delegate, passing the row value (i.e., data from your model that corresponds to the selected index path). Use the optional ? operator so that if the delegate was not set, nothing bad happens.

    tableRowSelectionDelegate?.tableRowSelected(rowValue)
    
  4. Add the protocol to your view controller.

    class ViewController: UIViewController, TableRowSelectionDelegate
    
  5. In your view controller, set it as the delegate for your table view class.

    tableViewClass.tableRowSelectionDelegate = self
    
  6. Implement the protocol in your view controller.

    func tableRowSelected(rowValue: String) {
        //perform the segue here...
        //  if necessary, pass the row value to the destination
        //  view controller before performing the segue
    }
    

This delegate protocol can now be implemented by all the view controllers that use your table view class, and each view controller can respond however it wants. Perhaps you won't always want to segue. Let the delegate decide.

Upvotes: 1

CTCoder
CTCoder

Reputation: 23

First, I want to recommend Apple's documentation Adding a Segue Between Scenes in a Storyboard.

You definitely place your UITableView on a view controller and setup the UITableViewDelegate, UITableViewDataSource on storyboard so that your view controller can know which row does the user select.

Upvotes: 0

Related Questions