如何在 UITableView Xamarin.ios 中的所需索引处插入行?

How to insert row at desired index in UITableView Xamarin.ios?

我想在所选行索引旁边的索引上添加几行。 例如,如果我单击了索引 4 处的行,我希望在索引 5、6、7 处添加一些行。并且这些索引的实际行在 8、9、10 等处向前移动

在您的 table 查看源代码 MyTableViewSource 中,您必须覆盖 RowSelected。在这种方法中,你检查你的行号并添加项目到你 table 查看源的 Items 添加它们之后,你必须调用 ReloadData().

class MyTableViewSource : UITableViewSource
{
    private readonly UITableView _table;
    public List<string> Items { get; }

    public MyTableViewSource(UITableView table)
    {
        _table = table;
        Items = new List<string> { "Hello", "World", "Bla", "Foo" };
    }

    public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
    {
        var item = Items[indexPath.Row];
        var cell = // create cellfor item
        return cell;
    }

    public override nint RowsInSection(UITableView tableview, nint section)
    {
        return Items.Count;
    }

    public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
    {
        if (indexPath.Row == 2)
        {
            Items.Insert(3, "Horst");
            Items.Insert(4, "Klaus");
            Items.Insert(5, "Peter");
            _table.ReloadData();
        }
    }
}

创建它们:

var table = new UITableView();
table.Source = new MyTableViewSource(table);

如果你想更好地控制动画,你可以使用这个版本:

public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
    if (indexPath.Row == 2)
    {
        _table.BeginUpdates();
        Items.Insert(3, "Horst");
        Items.Insert(4, "Klaus");
        Items.Insert(5, "Peter");

        _table.InsertRows(new[] { NSIndexPath.Create(0, 3), NSIndexPath.Create(0, 4), NSIndexPath.Create(0, 5) }, UITableViewRowAnimation.Left);
        _table.EndUpdates();
    }
}