我已经阅读了所有与此相关的帖子,但我仍然有一个错误:

'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (5) must be equal to the number of rows contained in that section before the update (5), 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).'

以下是详细情况:

我的.h分是NSMutableArray分:

@property (strong,nonatomic) NSMutableArray *currentCart;

.m,我的numberOfRowsInSection看起来是这样的:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.


    return ([currentCart count]);

}

要启用删除并从数组中删除对象,请执行以下操作:

// Editing of rows is enabled
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {

        //when delete is tapped
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

        [currentCart removeObjectAtIndex:indexPath.row];


    }
}

我认为,通过让我的区段数依赖于我正在编辑的数组的计数,可以确保适当的行数?在删除行时,不需要重新装入表就可以做到这一点吗?

推荐答案

您需要从您的数据数组before(称为deleteRowsAtIndexPaths:withRowAnimation:)中删除该对象.因此,您的代码应该如下所示:

// Editing of rows is enabled
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {

        //when delete is tapped
        [currentCart removeObjectAtIndex:indexPath.row];

        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

您还可以通过使用数组创建快捷键@[]来稍微简化代码:

[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

Ios相关问答推荐

如何保持拖动预览与原始项目完全相同?

如何在SwiftUI中为带有CornerRadius的矩形创建下边框?

如何在expo-react native中从ios平台中排除包

无法使用 NavigationView 和 NavigationLink 在 SwiftUI 中弹出当前屏幕

将 Riverpod 从 StateNotifier 修复为 NotifierProvider 以及应用程序生命周期监控

NSError 错误领域: "CBATTErrorDomain" 代码: 128 0x0000000282b111a0

不使用故事板创建 iMessage 应用程序

更新 flutter 和 xcode 后 Xcode 14.3 中缺少文件 (libarclite_iphoneos.a)

UIView 阴影不适用于自定义扩展

如何使用 pushViewController 从 UIHostingController 的 SwiftUI 视图中推送 ViewController?

将 SwiftUI 与 @AppStorage 和动态函数调用一起使用

通过按钮打开 AppStore

实现一个将块用作回调的方法

如何判断 `NSManagedObject` 是否已被删除?

本月使用 iOS 的天数?

将图像保存到 Documents 目录并检索邮箱附件

如何使用 Swift 从assets资源 中加载特定图像

为所有 UIImageViews 添加圆角

iOS7 UITextView contentsize.height 替代

AFNetworking 2.0 向 GET 请求添加标头