Hiding a UITableView section along with all the rows in it

150 views Asked by At

I have 2 sections on my UITableview controller. One of my section has a switch and my requirement is when I set the switch to ON, the second section should be set to hidden along with all its rows. I am calling the following method/code to hide the section when the status of the switch is changed:

- (void)setState
{
    myTableViewCell *myCell = [[myTableViewCell alloc] init];
    if ([myCell.mySwitch isOn])
    {
        NSIndexPath *indexPath = [NSIndexPath indexPathWithIndex:1];
        [self.tableView cellForRowAtIndexPath:indexPath].hidden = YES;
    }
}

I am getting the following exception for this code which I understand is perfectly true.

Name = NSInternalInconsistencyException;
Reason = "Invalid index path for use with UITableView.  Index paths passed to table view must contain exactly two indices specifying the section and row.  Please use the category on NSIndexPath in UITableView.h if possible.";

But how can I hide the complete section along with all its rows. If I try to get the index path using NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1]; this would just hide the 1st row in the section.

2

There are 2 answers

0
Eric Qian On

If you wanna hide a whole section when switch is on, just reloadData when you click the switch, and return 0 in numberOfRowsInSection for that section and return totalNumberOfSections - howManySwitchesIsOn in numberOfSectionsInTableView, like this:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView   
{  
    if(howManySwitchesIsOn) {
        return totalNumberOfSections - howManySwitchesIsOn; 
    } 
    return totalNumberOfSections;
}  

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section   
{  
    if(section should be hide) {
         return 0;
    }
    return howManyRowsForThatSection;
} 
0
Marco On

Section deletion and insertion in a grouped UITableView are accomplished via:

- (void)deleteSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation
- (void)insertSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation

Check out SectionHidingDemo, a demo app that illustrates section deletion and insertion in a grouped UITableView using those methods.