David David - 2 months ago 24
Swift Question

Which component should be used to create Cards in iOS?

I would like to create an app in which users can scroll to see cards, dynamically created (like Facebook's app). Which component is more appropriate for this purpose?


  • Reusable UIView inside UIScrollView? (performance?)

  • UIStackView inside UIScrollView? (...?)

  • UITableCellView inside UITableView? (don't think so)



I want it to have some shadow and a dynamic height depending on the content.

Thank you.




Picture
enter image description here

Answer

If you want to create something similar to a News Feed like on Facebook, then using a UITableView is the way to go. Depending on how many different kinds of card layouts you want, you could create a different dynamic prototype UITableViewCell for each card layout. UITableViews are the most natural for this and are also great for performance. It is basically what you first alluded to by saying "Reusable UIView inside UIScrollView". UITableView is a UIScrollView, and the UITableViewCells are basically UIViews and yes, they do get reused. At any given time, there are only enough cells needed to show what is on the screen. If you have 100 items in your News Feed, there will still only be maybe 7 cells, and as you scroll through the News Feed the 7 cells will be reused to create different items on the News Feed.

For dynamic heights: You won't be able to explicitly state that you want dynamic heights in the Storyboard. Instead what you do is for your label with varying height, make the lines attribute equal to 0. Once that equals to 0, then you need to make sure you have constraints all properly placed from the top to the bottom of the cell. You may have many elements, but iOS needs the constraints to be perfect so that it can unambiguously determine the height.

In the corresponding View Controller, you write the following in your viewDidLoad method:

tableView.rowHeight = UITableViewAutomaticDimension

Then, I recommend also doing tableView.estimatedRowHeight = 150 or something like that so that your scrolling won't be as wonky.

The 100% solution for scrolling (especially scrolling up) not to get wonky because it usually does with dynamic cell heights is to implement the tableView delegate method tableView(:heightForRowAtIndexPath) method.

That said, this is just a tiny precursor on how to get that started. The topic of dynamic heights can be found with lots of tutorials on the web and also numerous questions on Stackoverflow about the problems people run into.

Comments