尝试在iOS中将新行动态添加到UITableView

sye*_*dfa 3 objective-c uitableview ios

我的应用程序中有一个UITableView,我想通过单击一个按钮向其中动态添加行。当用户单击我的按钮时,将调用以下方法:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

然后调用:

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

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

}
Run Code Online (Sandbox Code Playgroud)

问题是,尽管我已经实现了UITableViewDelegate和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];
    }   
}
Run Code Online (Sandbox Code Playgroud)

有人可以看到我在做什么错吗?

Pau*_*w11 5

您需要在表格数据数组中插入另一行,然后调用insertRowsAtIndexPaths表格视图以使表格视图知道新行。新行将在数组的末尾,因此行数为1。

[self.tableData addObject:newObject];
NSIndexPath *newPath=[NSIndexPath indexPathForRow:self.tableData.count-1 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[newPath] withRowAnimation:UITableViewRowAnimationAutomatic];
Run Code Online (Sandbox Code Playgroud)