尝试动态地向iOS中的UITableView添加新行

时间:2015-10-11 21:12:50

标签: ios objective-c uitableview

我的应用程序中有一个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];
}

然后调用:

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

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

}

问题是,尽管我实现了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];
    }   
}

任何人都可以看到它的错误吗?

2 个答案:

答案 0 :(得分:5)

您需要在表数据数组中插入一行,然后在tableview上调用insertRowsAtIndexPaths,让表视图知道新行。新行将位于数组的末尾,因此行count-1。

[self.tableData addObject:newObject];
NSIndexPath *newPath=[NSIndexPath indexPathForRow:self.tableData.count-1 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[newPath] withRowAnimation:UITableViewRowAnimationAutomatic];

答案 1 :(得分:2)

您应该在UITableView上执行插入或删除操作:

[tableView beginUpdates];

// Add object to the array
[self.tableData addObject:theObjectToInsert];

// perform tableView insertion/delete here
[tableView insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationAutomatic];

[tableView endUpdates];