How to create UITableView with multilevel expandab

2019-04-10 06:34发布

问题:

I have to create a table view (iPad app) that is able to show and collapse rows at different levels:

- Client 1
 - Category 1
  - Info 1
  - Info 2
 - Category 2
  - Info 1
  - Info 2
 - Category 3
  - Info 1
  - Info 2
- Client 2
 - Category 1
  - Info 1
  - Info 2

and so on...

If the user taps on a client row, the whole client related rows (Categories and infos under that client) should expand/collapse. In the other hand, if they tap on a particular Category only that category should expand/collapse.

So i'm planning to have nested NSMutableDictionaries to hold data which i can access by dynamic keys (like dynamic client names) but i'm not sure this approach will actually work to resolve the actual problem (make collapsible parts). Also, I'm not sure if using only rows and make them appear like header sections or use actual sections, because as far as i know i can not make sub-sections to achieve the three level nesting.

Any ideas? I've seen examples of projects with expandable rows but i'm still confused.

Help!

回答1:

The TLIndexPathTools library on GitHub is pretty well suited for this sort of thing. To demonstrate, I put together a simple collapsible tree viewer component. It supports any tree depth using cells at each level. Try running the "Outline" sample project.

The tree component is a work-in-progress, but hopefully it should be a good start.



回答2:

I think nested dictionaries would be inconvenient for – tableView:cellForRowAtIndexPath:.

Here's a lazy solution:

Use a NSMutableArray and UITableView with rows disguised to look like sections. The objects in the array would each have a property called children of type NSMutableArray. When expanding a parent item, empty the children array and insert them following the parent. When collapsing, keep moving items into children until it hits an item of the same level as the parent.

Then for animation: – insertRowsAtIndexPaths:withRowAnimation: or – deleteRowsAtIndexPaths:withRowAnimation:. Either UITableViewRowAnimationTop or UITableViewRowAnimationFade would look nice.