gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 17:05:29 26 4
gpt4 key购买 nike

我的应用程序中有一个 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,但我已经实现的以下委托(delegate)方法都没有被调用:

- (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];
}
}

谁能看出我做错了什么?

最佳答案

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

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

关于ios - 尝试向 iOS 中的 UITableView 动态添加新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33070184/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com