簡體   English   中英

在 uitableview 的同一部分中插入/創建新行

[英]insert/create new row in a same section of uitableview

我遇到了一個問題,我有一個 uitableview 行,比如說 5。如果用戶選擇一行,那么應該使用 animation 創建/插入恰好位於點擊行下方的新行(正如我們已經看到的部分隱藏/取消隱藏) 並且在點擊新插入的行時,它應該被刪除。

我試過了,但它說


Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid  
update: invalid number of rows in section 0.  The number of rows contained in an existing section 
after the update (6) must be equal to the number of rows contained in that section before the update 
(5), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted).'

那么實現此功能的另一種方法應該是什么? 提前致謝。

最初你有 5 行。 您向表中添加一個新行,比如說使用 addRowsAtIndexPaths: 方法。 此時,您的表格視圖將調用其數據源方法,因為它需要添加這個新單元格。

但是,可能您仍然從數據源方法返回的行數為 5(而不是 6),這導致不一致(因為表視圖需要 6 行,而您仍然返回 5 行)

因此,假設當表格視圖為新創建的單元格(行 = 5)調用 cellForRowAtIndexPath: 方法時,它可能會崩潰,因為您必須執行以下操作:

[yourDatasourceArray objectAtIndex:indexPath.row];

上面的語句會導致崩潰,因為 indexPath.row 是 5 並且您的數組中仍然有 5 個對象(索引 0 到 4)。 因此 objectAtIndex:5 導致崩潰。


- (NSInteger)numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return numberOfRows;
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    numberOfRows ++;
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSMutableArray*  tempArray = [[NSMutableArray alloc] init];
        [tempArray addObject:[NSIndexPath indexPathForRow:indexPath.row +1  inSection:indexPath.section]];
    [tableView beginUpdates];
    [tableView insertRowsAtIndexPaths:tempArray withRowAnimation:UITableViewRowAnimationRight];
    [tableView endUpdates]; 
    [tempArray release];

}



我犯了 2 個錯誤 1) 我沒有使用 [tableView beginUpdates] 並且顯然在更新后 [tableView endUpdates] 2) 計算 newRow 的 indexpath 的方法是模棱兩可的。

非常感謝 pratikshabhisikar 和 Max Howell 投入時間和精力。

暫無
暫無

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

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