UITableViewDelegate 中用于删除单元格的 NSInternalInconsistencyException 错误 / Xamarin.iOS

NSInternalInconsistencyException error in UITableViewDelegate for deleting a cell / Xamarin.iOS

我想在 Xamarin.iOS 的 table 视图中有两个正常滑动操作(这意味着从右到左)。

当我搜索时,我知道我可以为我的 table 自定义一个 UITableViewDelegate 并使用不同的动作进行滑动。

这是我的 UITableViewDelegate 代码:

public class NotificationTableDelegate : UITableViewDelegate
{
    private readonly AlertsViewController _AlertsViewController;
    private List<NotificationItem> _notifications;

    public NotificationTableDelegate(AlertsViewController tagViewController, List<NotificationItem> notifs)
    {
        _AlertsViewController = tagViewController;
        _notifications = notifs;
    }

    public override UITableViewRowAction[] EditActionsForRow(UITableView tableView, NSIndexPath indexPath)
    {
        UITableViewRowAction activateOrDeactivateNotifAction = UITableViewRowAction.Create(
            UITableViewRowActionStyle.Normal,
            "activate",
            delegate {
                //activate or deactivate 
            }
        );

        UITableViewRowAction deleteNotifAction = UITableViewRowAction.Create(UITableViewRowActionStyle.Destructive,"Delete",async delegate
        {
            UIAlertController alert = UIAlertController.Create(_notifications.ElementAt(indexPath.Row).Label, "ConfirmDeleteAlert", UIAlertControllerStyle.Alert);
            alert.AddAction(UIAlertAction.Create("Yes", UIAlertActionStyle.Destructive, (action) => {
                _notifications.RemoveAt(indexPath.Row);
                tableView.DeleteRows(new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade);
            }));
            alert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, (action) => { }));
            await _AlertsViewController.PresentViewControllerAsync(alert, true);
        });
        return new UITableViewRowAction[] { deleteNotifAction, activateOrDeactivateNotifAction };

    }
}

在那里,我有两个动作,"activate" 和 "delete"。直到这里,一切正常但是,删除操作让我出错。 当我删除一行并接受删除后,它使我出现 NSInternalInconsistencyException 错误:

Objective-C exception thrown. Name: NSInternalInconsistencyException Reason: Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (7) must be equal to the number of rows contained in that section before the update (7), 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).

我认为错误是正确的,因为 Table 中的单元格数量必须更改,但在 NotificationTableDelegate 中我无法访问 UI[=30 中的项目=]查看源代码!如何解决此错误或如何修改 UITableViewSource 中的项目?任何想法?

*我有使用 CommitEditingStyle 等在 UITableViewSource 中进行删除的代码...但我的情况并非如此。 此外,我还有 CanEditRow,在 UITableViewSource 中为真。

您可以使用 Source 的 tableview 代替。

这个class包括UITableViewDelegate + UITableViewDataSource

中的所有方法