簡體   English   中英

在新視圖中的tableview中插入一行

[英]Inserting a row in a tableview in a new section

我從帶有一個部分的tableview開始,第一部分總是有三行。 下載了一些內容后,我想在第二部分中顯示一個新單元格,所以我這樣做:

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

但我得到一個NSInternalConsistencyException:

由於未捕獲的異常'NSInternalInconsistencyException'而終止應用程序,原因:'無效更新:無效的節數。 更新后的表視圖中包含的節數(2)必須等於更新前的表視圖中包含的節數(1),加上或減去插入或刪除的節數(0插入,0刪除)。”

為什么不自動插入新的部分,如果我插入一個部分,那么在插入不在新部分中的行時會出現問題。

為什么不能自動添加新的部分? 當然,InsertRowAtIndexpath:還包括在必要時插入一個部分,因為NSIndexPath還包含一個部分。

[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;
}

將其保存在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];

這應該適合你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM