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?
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With