Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to add a new row dynamically to a UITableView in iOS

I have a UITableView in my app to which I am trying to dynamically add rows to, by clicking a button. When the user clicks my button, the following method is called:

- (IBAction)addChoice:(id)sender {
    //addRow is a boolean variable that is set so that we can use it to check later and add a new row
    if (!self.addRow) {
        self.addRow = YES;
    }

    [self setEditing:YES animated:YES];
}

which then calls:

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {

    [super setEditing:editing animated:animated];
    [self.choiceTable setEditing:editing animated:animated];

}

The problem, is that neither of the following delegate methods that I have implemented are being called, despite my having implemented UITableViewDelegate, and UITableViewDataSource:

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (self.addRow) {
        return UITableViewCellEditingStyleInsert;
    } else {
        return UITableViewCellEditingStyleDelete;
    }
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    NSArray *indexPathArray = [NSArray arrayWithObject:indexPath];

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [self.tableData removeObjectAtIndex:indexPath.row];
        NSArray *indexPathArray = [NSArray arrayWithObject:indexPath];
        [tableView deleteRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        NSString *theObjectToInsert = @"New Row";
        [self.tableData addObject:theObjectToInsert];
        [tableView reloadData];
        [tableView insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationAutomatic];
    }   
}

Can anyone see what it is I'm doing wrong?

like image 826
syedfa Avatar asked Sep 17 '25 08:09

syedfa


1 Answers

You need to insert an additional row into your table data array and then call insertRowsAtIndexPaths on your tableview to let the table view know about the new row. The new row will be at the end of the array, so row count-1.

[self.tableData addObject:newObject];
NSIndexPath *newPath=[NSIndexPath indexPathForRow:self.tableData.count-1 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[newPath] withRowAnimation:UITableViewRowAnimationAutomatic];
like image 125
Paulw11 Avatar answered Sep 19 '25 05:09

Paulw11