簡體   English   中英

moveRowAtIndexPath:一旦最后一行移動到另一個部分,如何刪除部分

[英]moveRowAtIndexPath: how to delete section once last row is moved to another section

我有幾個部分的tableview。 我希望能夠將行從一個部分移動到另一個部分,並在沒有行時刪除部分。 我試圖通過moveRowAtIndexPath執行此操作,但我的代碼不起作用並拋出NSRangeException異常。

這是一個代碼示例:

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {

    NSUInteger fromSection = [fromIndexPath section];
    NSUInteger fromRow = [fromIndexPath row];
    NSString *fromKey = [self.keys objectAtIndex:fromSection];
    NSMutableArray *fromEventSection = [self.eventsDict objectForKey:fromKey];

    NSUInteger toSection = [toIndexPath section];
    NSUInteger toRow = [toIndexPath row];
    NSString *toKey = [self.keys objectAtIndex:toSection];
    NSMutableArray *toEventSection = [self.eventsDict objectForKey:toKey];

    id object = [[fromEventSection objectAtIndex:fromRow] retain];
    [fromEventSection removeObjectAtIndex:fromRow];
    [toEventSection insertObject:object atIndex:toRow];
    [object release];
    // The above code works just fine!

    // Try to delete an empty section. Here is where trouble begins:
    if ((fromSection != toSection) && [fromEventSection count] == 0) {
        [self.keys removeObjectAtIndex:fromSection];
        [self.eventsDict removeObjectForKey:fromKey];

        [tableView deleteSections:[NSIndexSet indexSetWithIndex:fromSection] withRowAnimation:UITableViewRowAnimationFade];
    }

通過在dispatch_async中包裝刪除,我很幸運在moveRowAtIndexPath方法結束后的塊中執行了deleteSections方法。

    dispatch_async(dispatch_get_main_queue(), ^{
        if ((fromSection != toSection) && [fromEventSection count] == 0) {
            [self.keys removeObjectAtIndex:fromSection];
            [self.eventsDict removeObjectForKey:fromKey];
            [tableView deleteSections:[NSIndexSet indexSetWithIndex:fromSection] withRowAnimation:UITableViewRowAnimationFade];
        }
    });

這也讓我有些悲痛。 我已成功使用延遲執行部分刪除。

以下是我如何使用它 - 假設您使用商店來包含所有對象,並且商店有移動項目的方法:

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
    NSInteger beforeSectionCount = [store sectionCount];
    [store moveObject:fromIndexPath toIndexPath:toIndexPath];
    if (beforeSectionCount > [store sectionCount]
        [self performSelector:@selector(deleteSection:) withObject:fromIndexPath: afterDelay:0.2]
}

- (void)deleteSection:(NSIndexPath *)indexPath {
    [[self tableView] beginUpdates];
    [[self tableView] deleteSections:[NSIndexSet indexSetWithIndex:[indexPath section]]
                withRowAnimation:UITableViewRowAnimationFade];
    [[self tableView] endUpdates];
}

暫無
暫無

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

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