<分区>
<分区>
我想通过使用 alertView 消息来确认从 tableView 中删除一行,但是得到了一些错误输出:
reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (3) must be equal to the number of rows contained in that section before the update (3), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
在SomeViewController接口(interface)中设置一些私有(private)成员
@interface SomeViewController ()
{
NSMutableArray *listItems;
NSString *itemId;
NSIndexPath *rowIndexPath;
}
在 SomeViewController.m 中
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return [listItems count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[listItems objectAtIndex:section] count];
}
#pragma mark - Table view operation
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//add code here for when you hit delete
UIAlertView *deleteAlert = [[UIAlertView alloc] initWithTitle:@"Message"
message:@"Are you sure?"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:@"Cancel", nil];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
itemId = cell.textLabel.text;
rowIndexPath = indexPath;
deleteAlert.tag = 1;
[deleteAlert show];
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView.tag == 1)
{
if (buttonIndex == 0) {
NSLog(@"itemId: %@", itemId);
NSLog(@"rowIndexPath: %@", rowIndexPath);
[self.tableView beginUpdates];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:rowIndexPath]
withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];
[self.tableView reloadData];
}
}
}
我可以正确设置 tableView 数据并显示删除选项,但无法弄清楚为什么会出现该错误。
最佳答案
在删除单元格之前删除数据源。
希望对你有帮助
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView.tag == 1)
{
if (buttonIndex == 0) {
NSLog(@"itemId: %@", itemId);
NSLog(@"rowIndexPath: %@", rowIndexPath);
[self.tableView beginUpdates];
[[listItems objectAtIndex:section] removeObjectAtIndex:rowIndexPath.row]
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:rowIndexPath]
withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];
[self.tableView reloadData];
}
}
关于ios - 如何从 UITableView 中删除一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20793906/