简体   繁体   中英

Inserting a row in a tableview in a new section

I start with a tableview with one section, the first section always has three rows. After some content has downloaded, I want show a new cell, in a second section, so I do :

[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];

But I get an NSInternalConsistencyException:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections. The number of sections contained in the table view after the update (2) must be equal to the number of sections contained in the table view before the update (1), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted).'

Why isn't it inserted the new section automatically, If I do insert a section, then I get problems when inserting rows that are not in new sections.

Why can't it just add the new section automatically? surely InsertRowAtIndexpath: also include inserting a section if necessary as an NSIndexPath also includes a section.

[self.tableView insertSections:nsIndexSetToInsert withRowAnimation:UITableViewRowAnimationAutomatic];

and don't forget to set numberOfSectionsInTavleView and numberOfRowsInSection accordingly.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    NSInteger numberOfSections;
    if (condition1) {
        numberOfSections = 2;
    } else if (condition2) {
        numberOfSections = 3;
    } else {
        numberOfSections = 4;
    }

    return numberOfSections;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section
    if(section == 1) return 3;
    else return numberOfRows;
}

Keep this in ViewDidLoad

childArray1 = [[NSMutableArray alloc] initWithObjects: @"Apple", @"Microsoft", @"HP", @"Cisco", nil];
childArray2 = [[NSMutableArray alloc] init];
parentArray = [[NSMutableArray alloc] initWithObjects:childArray1, nil];

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
     return [parentArray count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
      NSInteger rowCount ;
      if (section == 0)
      {
           rowCount = [childArray1 count];
      }
      else
      {
           rowCount = [childArray2 count];
      }
      return rowCount;
}

Once your content is downloaded from server.

 if([childArray2 count] > 0)
     [parentArray addObject : childArray2];
 [tableView reloadData];

This should work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM