【问题标题】:table view cell deleting not working表格视图单元格删除不起作用
【发布时间】:2010-08-22 20:23:21
【问题描述】:

我使用 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 但是没有任何效果。

【问题讨论】:

    标签: ios iphone uitableview


    【解决方案1】:

    嗯,基本上你想做的是:

    1. 从数据源(数组)中删除行。
    2. 告诉表视图您已从数据源中删除了一行。

    正确的代码应该是这样的:

    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: 方法。

    在您的其他视图控制器中(可能是 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。

    【讨论】:

    • 非常感谢。 (我的问题的旁注我有一个数据数组,该数组从另一个控制器复制到具有表的那个。有没有办法从该数组中删除一个对象而不必重新复制整个数组,如果它再次nsuserdefault它被删除了?)
    • 我已经在答案中添加了一些示例代码,无法编辑我的评论,因为它已经被编辑过。通常,您希望将其他 ViewController 注册为观察者,并在删除对象时向其发布通知。
    【解决方案2】:

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

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

    必须比以前少一个。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      相关资源
      最近更新 更多