Search code examples
iosuitableviewios7

showing and hiding a specific cell type in a UITableView (possibly with animation)


I have a UITableView and have seen this effect and would like to implement it for our the followind data:

menu_header
  menu_subheader
    * item
    * item
  menu_subheader
    * item
    * item  
    * item

Basically, I would like to show just the header and subeaders and then when the user clicks one of the subheaders, it displays the items (preferably in an animation block) AND adjusts the other cells down or up appropriately. Like this:

enter image description here

Is there a prebuilt component that does this? Thinking about it, it seems like I would like to set these item cells to be hidden. I have seen this https://github.com/peterpaulis/StaticDataTableViewController but it looks like it doesn't work with dynamic data. It seems like this should be really simple. Any ideas on how to get this done? Ideally, I'd like it to be able to when you click it insert the data and then if you click another sub-header, close the other one and add to that sub-header.


Solution

  • To implement "folding" in a table view you have two options:

    • Control the number of cells in a section based on a folded/unfolded property per section. When folding or unfolding, use the insert or deleteRowsAtIndexPaths:withRowAnimation: methods on the tableView.
    • Control the height of the cells using the delegate method. Return zero for folded sections based on a folded/unfolded property per section. When folding or unfolding, call beginUpdates followed immediately by endUpdates to re compute the heights and animate to the new layout.

    I've created a simple implementation of the second option in this GitHub repo. Please let me know if you have other questions about it.