Search code examples
uitableviewuikit

Why is `heightForRowAt` implemented in `UITableViewDelegate` and not `UITableViewDataSource`?


This question is a bit more pedagogical in nature, but why is heightForRowAt implemented in UITableViewDelegate and not UITableViewDataSource?

Doesn't it make more sense for row height to be defined in UITableViewDataSource?

Since the height of a row should depend on the contents of that particular row, and therefore by extension the data source?


Solution

  • A Tableview is a pretty complex view and aas a view it must be reusable. This can only be achieved if some of the aspects of a table view are left to other classes. The table view uses two classes a delegate and a datasource.

    The datasource is responsible for the data that needs to be shown in the table. This dat comes from a model object in the MVC paradigm.

    The delegate is responsible for how the table should represent itself. Although the height of a row is a piece of data and might give you the idea that it should be a method of the datasource, the height of a row sets a layout item of the table view and therefore the representation of the table view.

    For this reason heightForRowAt is a delegate method and not a datasource method.