5

I'm trying to delete or hide a section inside a tableview with static cells on it. I am trying to hide it in function viewDidLoad. Here is the code:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.tableView beginUpdates];
    [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:YES];
    [self.tableView endUpdates];

    [self.tableView reloadData];
}

Still the sections appear. I am using storyboards in it. Can you please help me out?Thanks!

WrightsCS
  • 50,551
  • 22
  • 134
  • 186
user1096503
  • 91
  • 2
  • 4

4 Answers4

7

I found it most convenient to hide sections by overriding numberOfRowsInSection.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ( section == 1 )
        // Hide this section
        return 0;
    else
        return [super tableView:self.tableView numberOfRowsInSection:section];
}
masc3d
  • 409
  • 4
  • 3
5

Check the answer found here. How to remove a static cell from UITableView using Storyboards Seems to be a bugger of a problem when using static cells. Hope this helps.

Community
  • 1
  • 1
Bill Burgess
  • 14,054
  • 6
  • 49
  • 86
0

Here you go. This one also removes the vertical space.

NSInteger sectionToRemove = 1;
CGFloat distance = 10.0f; // minimum is 2 since 1 is minimum for header/footer
BOOL removeCondition; // set in viewDidLoad

/**
 *  You cannot remove sections.
 *  However, you can set the number of rows in a section to 0,
 *  this is the closest you can get.
 */

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section {
  if (removeCondition && section == sectionToRemove)
    return 0;
  else
    return [super tableView:self.tableView numberOfRowsInSection:section];
}

/**
 *  In this case the headers and footers sum up to a longer
 *  vertical distance. We do not want that.
 *  Use this workaround to prevent this:
 */
- (CGFloat)tableView:(UITableView *)tableView
    heightForFooterInSection:(NSInteger)section {

  return removeCondition &&
                 (section == sectionToRemove - 1 || section == sectionToRemove)
             ? distance / 2
             : distance;
}

- (CGFloat)tableView:(UITableView *)tableView
    heightForHeaderInSection:(NSInteger)section {

  return removeCondition &&
                 (section == sectionToRemove || section == sectionToRemove + 1)
             ? distance / 2
             : distance;
}
RyuX51
  • 2,779
  • 3
  • 26
  • 33
-2

It seems that reloadData makes table view to re-read dataSource. You should also remove data from dataSource before calling reloadData. If you are using array, remove object you want with removeObject: before calling reloadData.

Nik
  • 9,063
  • 7
  • 66
  • 81