表视图单元格删除不起作用

时间:2010-08-22 20:23:21

标签: ios iphone uitableview

我已经使用sdk标准代码进行删除,但是一旦按下删除按钮就会崩溃。 我正在使用此代码

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[tableFavoritesData arrayWithObject:indexPath] withRowAnimation:YES];
    }
}

我尝试使用NSMutableArray而不是tableFavoritesData但是没有任何效果。

2 个答案:

答案 0 :(得分:2)

嗯,基本上你想做的是:

  1. 从数据源(数组)中删除行。
  2. 告诉表格视图您已从数据源中删除了一行。
  3. 正确的代码可能应该是这样的:

    if (editingStyle == UITableViewCellEditingStyleDelete) {
     [tableFavoritesData removeObjectAtIndex:indexPath.row];
     [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
     }   
    
    编辑:我没有注意到其他错误。

    您需要指定动画类型,而不仅仅是传递YES或NO。例如:UITableViewRowAnimationFade。查看可能的UITableViewRowAnimation值here

    编辑2:对于下面的评论(评论格式很糟糕): 查看文档中的NSNotificationCenter,尤其是addObserver:selector:name:object:和postNotificationName:object:methods。

    在您的其他视图控制器中(可能是viewDidLoad方法):

    [[NSNotificationServer defaultCenter] addObserver:self selector:@selector(deletedRow:) name:@"RowDeleted" object:nil];
    
    -(void) deletedRow:(NSNotification*) notification
    {
      NSDictionary* userInfo = [notification userInfo];
      NSIndexPath indexPath = [userInfo objectForKey:@"IndexPath"];
     // your code here
    }
    

    并删除行:

    if (editingStyle == UITableViewCellEditingStyleDelete) {
    ...
    [[NSNotificationServer defaultCenter] postNotificationName:@"RowDeleted" object:self userInfo:[NSDictionary dictionaryWithObject:indexPath forKey:@"IndexPath"]];
         }   
    

    请记住,在释放其他UIViewController时需要从通知中心删除观察者:

    [[NSNotificationServer defaultCenter] removeObserver: self];
    

    希望我没有犯很多错误,我无法访问XCode atm。

答案 1 :(得分:0)

如果您查看控制台,它很可能会告诉您模型(您的数据结构)与表所期望的不匹配。即你的委托方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

必须比以前少一个。

此外,[tableFavoritesData arrayWithObject:indexPath]看起来很奇怪,可能不是预期的。也许你想要[NSArray arrayWithObject:indexPath]。并首先从模型中删除数据。

相关问题