Communicating between UIViewController and UITableViewDelegate

64 Views Asked by At

I have a UIViewController which contains a UITableView (amongst other views).

The UITableView could get its cells from one of two UITableDataSource, depending on some condition.

My UITableDataSource class also acts as my UITableViewDelegate.

When a cell is selected (tableView:didSelectRowAtIndexPath) I may want to perform an action on the UIViewController, such as performSegue or show an alert.

What would be the best way to do this?

  1. Add a weak reference to the UIViewController inside each datasource/delegate class
  2. Create a delegate per datasource/delegate class which calls functions inside my UIViewController
  3. Your suggestion here!

I considered making my UIViewController the UITableViewDelegate but as the cells are different depending on the source I thought it would get messy.

Note: I say "best way" but really I am just interested in alternate approaches

1

There are 1 best solutions below

2
FryAnEgg On

The most common approach is to subclass UITableViewController and implement UITableViewDelegate and UITableDataSource there. You can return whichever cell you require in cellForRowAtIndexPathbased on any state in your controller class.