I have a UITableView where in some instances, certain sections have zero rows. My goal is that when this is true, I don\'t want any wasted space in the table view, it should
My solution to this problem is on and off how h4xxr is describing however, I have a slightly different approach to constructing a dynamic number of sections.
Firstly, I define a method that will walk my data structure and flag wether or not the data should be shown in the table. This flag is stored in an array so that I can include as few or as many sections as I like. I can describe this implementation a little better if we focused on just the number of cells for each section:
Suppose my first section is to be contact details with first name, last name and age. I will define this section with an id of '1' (although technically as I explain later this could be any number). Now, if my method determines that this section should be visible, I push the value '1' onto an array.
The next section I wish to show is address and may have 3-4 rows/cells. As above, the logic in my method determines wether or not the address should be visible by pushing say '2' onto the array.
Now.. ..if we wanted both sections visible, we would have an array with a length of 2 and two items [1,2]. If we only wanted the contact details visible our array would have a length of 1 with items [1] and [2] for the address only.
Now we can return the length of our array to define the number of sections we want.
our switch statement would now look like something like this:
switch(ourArray[indexPath.section]){
case 1:
break;
case 2:
break;
case 3:
break;
}
Notice I've put case 3 in my switch. Because the array in our example only contains values '1' and '2', case 3 would never be matched and so ignored unless we decided to add / enable this case by pushing it to the array.
Note also that we can in our method that defines the logic of which sections are visible, change the order of the sections by inserting/pushing them at different locations in the array.
I use the above religiously as it allows me to decouple the indexing and construction of sections.
Finally, Before I update my table by using 'reloadData' I will call my method which will construct the array and provide the correct length and sequence of section id's to allow my tableview to know how to build itself. If my data changes or is filtered somehow, I will again call this method and reconstruct the array.