Embedding UIViewcontrollers inside UICollectionviewCells

In my application, I have a homepage with a card / grid with several sections. So a UICollectionView is an obvious choice. But these cards vary greatly in design, data loading and functionality. Thus, all those who are in one controller would be bulky, difficult and difficult to maintain. Therefore, we thought that we needed to split them into our own UIViewControllers . Each processes the type of card and calculates its contents, which will be displayed inside the card. Our main home page controller is responsible for placing these viewcontroller views inside UICollectionView cells.

To summerize,

  • HomeViewController that has a CollectionView
  • Each view inside the ViewCell collection and its data is supported by its own controller class.
  • All controller instances are inside the HomeViewController and added as its children . Apple Guide
  • The appearance for all children of the viewControllers is created by us, because the contentSize (which is used as the size of the element for the layout of the collection) for calculating the controller’s views requires the view to be loaded and the data to be set.

My question is, is this design right? Or what approach would you choose to implement such a screen? Since we create many viewControllers (one for each cell), does this affect memory or performance? And if I want to cache only some viewControllers or load them as the user scrolls or when it is time to add it to the collectionView cell, how do I do this, since the calculation of the size of this cell depends on the data and views when stacking from the CollectionView layout.

+5
source share
1 answer

I think that your approach really and from a theoretical point of view, it makes sense to separate the view from its data. But in this case, I would prefer the UICollectionViewCell subclass to implement its own data, basically acting as a viewController. This will simplify your code a bit, since you do not need the added viewControllers and the code that comes with them; instead, you can simply add your tableView to the cellView. This seems more natural to me, since then you can have the HomeViewController collectionView automatically handle the calls of its delegates when cells move off-screen and during the loading process. You will not need to send messages to the cells about who they are or when they should be loaded, all this will take care of you automatically. In addition, I really do not think that the presentation life cycle methods in each cell are valuable and less intuitive than the presence of loading and updating cells in a collection. Anyway, good luck!

+1
source

Source: https://habr.com/ru/post/1208749/


All Articles