Thursday, 16 March 2017

Parent-Child hierarchy using UITableView

UITableView gives us a way to list our data in a row where each row represents a one data. This data may vary from a single string to a composite object .

With UITableView we can show the parent child relationship to many indent level, like shown in this image:



You can implement above structure with UITableView, which will give you following functionality:
- Allow users to tap on one row to open and  close the sub tree , if selected row represents a parent.
- Automatic scrolling of data as new row instead and deleted with animation.

To implement this, follow these steps:
1) First of all create your iOS project and setup view and add a UITableView in your view controller. Also setup all necessary step like registering class for UITableView and set datasource and delegate appropriately. I am not telling all these basic step here. We will focus on how to implement above structure with UITableView only.

2) The key part of this application is data structure . Maintain your data in such a way that we can insert and delete row runtime and can distinguish between parent and child row.
   
For this I create a object which will tell all I need:

var nodeName:String
var isNodeChild:Bool
var arrChildren:[Node]
var indentLevel:Int


In starting we will show only parent node i.e. the node with indent level one.

3) In didSelectRowAtIndexPath: method of UITableView, check if this row represents a parent node and  this row already expanded to show the child node of the parent node or not.

We assume that row is not expended yet . If node for this row is parent , then get the number of children of this node and edit the main data source of your table view and insert the new rows to show the child of the node.

4) To show the difference between parent and child set the indent level of child row greater than the parent row.

5) To collapse the expanded parent , delete the child node of parent node i.e. First edit your data source and then delete the child row for the selected row.

Conclusion : We choose UITableView for this because UITableView provides much more we want. Automatic scrolling of data, easy insert and deleting of rows with animation . All we need here is to maintain the datasource of UITableView.

No comments:

Post a Comment