向tableView添加一行无法正常工作

时间:2015-03-04 06:52:43

标签: ios objective-c uitableview

我有自定义UITableView我正在尝试向tableView添加一行。这是我的代码:

- (IBAction)addRow:(id)sender
{
    NSInteger indexPath = [self.rowArray count] - 1;

    // I'm adding an object to an array of all the cell ids I have.
    [self.rowArray insertObject:@"rowSix" atIndex:indexPath];  // rowSix is a cell ID

    [self.myTableView beginUpdates];
    [self.myTableView endUpdates];

}

这是它输出的错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (8) must be equal to the number of rows contained in that section before the update (7), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

更新

cellForRowAtIndexPath

NSString *cellID = [self.rowArray objectAtIndex:[indexPath row]];
customCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];

2 个答案:

答案 0 :(得分:1)

试试这个 -

//Update data source with the object that you need to add
[tableDataSource addObject:newObject];

NSInteger row = //specify a row where you need to add new row
NSInteger section = //specify the section where the new row to be added, 

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
[self.tableView endUpdates];

答案 1 :(得分:1)

试试这个 -

    - (IBAction)addRow:(id)sender
    {
        [self.rowArray addObject:@"New Item"];
        NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:[self.rowArray count] inSection:0];
        [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];

    }