Reputation: 7996
I have a requirement to create controls dynamically at run-time based on config retrieved from server. I'm also trying to make use of MVVM pattern.
To keep example simple, lets say I have to create N
number of UILabels
in a View
, each with its own settings (color, font, etc.) all based on config from server.
First thing that comes to mind, is to have a listUILabels
property in my ViewModel
, and have the ViewModel
be responsible for creation of UILabel
objects and setting their attributes / properties (color, font, etc).
The View
would then iterate through each UILabel
in viewModel.listUILabels
adding each one via self.view.addSubview()
However I read in some examples, that the ViewModel
should not reference UIKit
, instead should just provide data, properties & enums for the View
(feel free to comment on this).
To adhere to MVVM rules, how should I partition my logic, what goes inside the View and what goes inside the ViewModel
in this case?
Upvotes: 0
Views: 547
Reputation: 39082
Basically the ViewModel
should be as independent on the View
as possible. It should be a representation of data that are related and logically belong on a single page, but it should not be dependent on the way the view itself is implemented or represented. Ideally it should be possible to change the view and its layout without having to modify the ViewModel
at all.
So your best course of action would be not to include a list of UILabels
in the ViewModel
and instead put a list of custom classes, that will store the "data" that you want to surface on the view. Because in this case you are dealing with UI related data, there should be no problem including color or font attributes as properties of these custom classes.
Then in the view itself you can observe this list and dynamically create appropriate controls (UILabels
) based on the provided data.
Upvotes: 0
Reputation: 2165
In my opinion your View class should contain the logic for creation of UILables and setting up its UI behavior based on the config settings.
ViewModel should provide the interfaces (properties) to interact with the underlying data which should update the View when data changes in your data source (model) and data source (model) should be updated when the data changes based on user interaction (if any).
Upvotes: 1