Can ViewModel class conforms to UITableviewDelegate and UITableViewDataSource in iOS as per MVVM

Viewed 2213

I have a viewcontroller which displays a table view with complex UI and different type of data depending on certain conditions/usertype. This involves logic to segregate and process data on user selection and hide/unhide expand/close section. As I am using MVVM pattern, can my viewmodel class conform to UITableviewDelegate and UITableViewDataSource, so that I have a thinner viewcontroller?

Something like -

class HomeViewController: UIViewController {

 .
 .

  let viewModel = HomeViewModel()

  @IBOutlet weak var tableView: UITableView!

 .
 .

  tableView.delegate = viewModel
  tableView.dataSource = viewModel
}

class HomeViewModel: UITableViewDataSource, UITableViewDelegate {

//Implement delegates

}
1 Answers

Yes you can, set any object that conforms to those protocols as the delegate, data source or separate them to different objects, anything and anyone can implement a protocol.

When writing a complex table view data source or delegate, It’s better to define a type whose purpose is to be a table view’s data source. This helps to better separate responsibilities between objects.

You can find an example by Apple implementing different objects as the table/collection View's data source here: Advanced User Interfaces with Collection Views by apple

These object/s doesn't have to be your viewModel, but please see a good example when it is: MVVM with viewModel as the table datasource

Related