iOS 以编程方式添加 UITableView 部分并重新加载它

iOS Add UITableView section programmatically and reload it

我想将节添加到 UITableView 并将行添加到这个新节 但是当我这样做的时候,应用程序崩溃了。

如何向 UITableView 添加数据并在不使用 UITableView.ReloadData() 的情况下重新加载数据。

这是我使用它的方法。

 private void AddToSection(UITableView tableView, List<TableItems> messages, bool reload = false)
  {

     foreach (var item in messages)
     {

        if (!_section.Contains(item.Section))
        {
           _sectionMessage.Add(new List<string>());
           _section.Add(item.Section);
           if (reload)
           {                  
              var index = NSIndexSet.FromIndex(_section.Count - 1);
              tableView.InsertSections(index, UITableViewRowAnimation.None);                  
           }

        }
        int section = _section.Count - 1;
        _sectionMessage[section].Add(item.Message);

        if (reload)
        {
           int row = _sectionMessage.LastOrDefault().Count-1;
           var index = new NSIndexPath[] {NSIndexPath.FromRowSection(row, section) };
           tableView.InsertRows(index, UITableViewRowAnimation.None);             
        }

     }
  }

先编辑: 您还必须更新数据源。您不能在不更新数据源的情况下向 tablView 添加新的部分和单元格。

/// 您尝试过以下方法吗?

tableView.beginUpdates()
tableView.endUpdates()

通常当您执行 reloadData() 并且没有正确更新数据源时,您会遇到类似您的问题。