Search code examples
swiftdynamiccontrollerprogrammatically-created

Set the TableView's controller class dynamically


I'd like to build an app that exposes sections in the TableView if the user clicks on a button. (The underlying data may also be sorted and filtered differently) This requires a few extra functions to be overridden and even some of the existing overridden functions require different implementations.

I was thinking that instead of putting if-statements in almost every overridden function it would be cleaner to have two different controller classes (in the IB defined in the "custom class" field) and change them programmatically when the user clicks on the button.

How can I reload my UITableView with a different controller class?

Thanks, Daniel


Solution

  • You can set either the dataSource or delegate for a UITableView at any time.

    An approach to take would be to have a main view controller holding on to the tableview, then in viewDidLoad assign either the datasource or delegate class instances you want the table to use.

    After you've done that, at any time you could change out the datasource/delegate for a new class instance, and ask the tableview to reload with the reloadData call.