I have a view model that contains my model and other properties used by my table view delegate methods in my view controller. For heightForRowAt delegate method, I’m passing a computed property from my viewmodel to dynamically calculate the height of the row. My question is does row height property belong to my viewmodel? What if it’s just a constant instead of computed property? If not, why? Should I put it inside another struct instead?
2 Answers
You can put it in either. There are different variations for MVVM.
Put it in view layer: If you prefer view model to not have any knowledge of view, then you can put the height calculation in your view model, because it is pure rendering logic. In this case, the view model is decoupled from the view very well, and you can use different views to present the same view model. The properties in your view model should be view independent, for example, you have a name label in your view, the the view model property should be called
name
instead ofnameLabelText
. There are two drawbacks of this implementation. First, if you want to cache the calculated height, then you have to implement cache in your view layer. The second is that it is not easy to calculate cell heights before rendering.Put it in view model: In practice, I found it is acceptable to let your view model have some knowledge of the view, because in most cases, one view model is only used by one view. In this case you can call your view model property
nameLabelText
if you like, and you can also havecellHeight
. It will also be easier to cache cell heights and do height calculations asynchronously.

- 2,395
- 15
- 22
If you want the pure MVVM implementation put it in the view layer because cell height belongs to the how the cell should display and it is a pure view logic, but it is acceptable to some extent you can put some view related code in the ViewModel.
To learn more about MVVM checkout this link about MVVM

- 230
- 3
- 12