【问题标题】:Inserting a row in a tableview in a new section在新部分的表格视图中插入一行
【发布时间】:2012-05-28 11:55:28
【问题描述】:

我从一个有一个部分的表格视图开始,第一部分总是有三行。下载一些内容后,我想在第二部分显示一个新单元格,所以我这样做了:

[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];

但是我得到一个 NSInternalConsistencyException:

由于未捕获的异常而终止应用程序 'NSInternalInconsistencyException',原因:'无效更新:无效 节数。表中包含的节数 更新后的视图(2)必须等于节数 更新前包含在表视图中(1),加减 插入或删除的部分数(0 插入,0 删除)。'

为什么它不自动插入新部分,如果我插入一个部分,那么在插入不在新部分中的行时会出现问题。

为什么不能自动添加新部分?当然 InsertRowAtIndexpath: 还包括在必要时插入一个部分,因为 NSIndexPath 也包括一个部分。

【问题讨论】:

    标签: iphone objective-c ios uitableview


    【解决方案1】:
    [self.tableView insertSections:nsIndexSetToInsert withRowAnimation:UITableViewRowAnimationAutomatic];
    

    别忘了相应地设置 numberOfSectionsInTavleView 和 numberOfRowsInSection。

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        // Return the number of sections.
        NSInteger numberOfSections;
        if (condition1) {
            numberOfSections = 2;
        } else if (condition2) {
            numberOfSections = 3;
        } else {
            numberOfSections = 4;
        }
    
        return numberOfSections;
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        // Return the number of rows in the section
        if(section == 1) return 3;
        else return numberOfRows;
    }
    

    【讨论】:

    • 我已经完成了第一行代码,其余代码按预期工作(否则不会抛出异常,至少不会抛出错误),如果我插入一个需要新部分的行,但如果将行插入现有部分会崩溃
    • 乔纳森,你到底是什么意思“我已经完成了第一行代码”和“其余的工作按预期工作”。基本上,这个答案告诉您,您有责任正确返回 numberOfSectionsInTableView: 和 tableView:numberOfRowsInSection: 的值。如果您插入一个新节,则前者必须正确返回新值,如果您在现有节中插入一行,则后者必须反映该更改。您必须将数据与更新 tableView 的尝试联系起来。这就是您的意思“我已经完成了第一行代码”和“其余工作按预期工作”吗?
    【解决方案2】:

    将其保存在 ViewDidLoad 中

    childArray1 = [[NSMutableArray alloc] initWithObjects: @"Apple", @"Microsoft", @"HP", @"Cisco", nil];
    childArray2 = [[NSMutableArray alloc] init];
    parentArray = [[NSMutableArray alloc] initWithObjects:childArray1, nil];
    
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
         return [parentArray count];
    }
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
          NSInteger rowCount ;
          if (section == 0)
          {
               rowCount = [childArray1 count];
          }
          else
          {
               rowCount = [childArray2 count];
          }
          return rowCount;
    }
    

    从服务器下载您的内容后。

     if([childArray2 count] > 0)
         [parentArray addObject : childArray2];
     [tableView reloadData];
    

    这应该适合你。

    【讨论】:

      猜你喜欢
      • 2012-07-05
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      • 2015-03-03
      相关资源
      最近更新 更多