Ios moveRowAtIndexPath:如何在最后一行移动到另一个节后删除节
我有一个包含几个部分的tableview。我希望能够将行从一个节移动到另一个节,并在没有行时删除一个节。我正试图通过MoveRowatineXpath执行此操作,但我的代码不起作用,并引发NSRangeException异常 下面是一个代码示例:Ios moveRowAtIndexPath:如何在最后一行移动到另一个节后删除节,ios,iphone,tableview,Ios,Iphone,Tableview,我有一个包含几个部分的tableview。我希望能够将行从一个节移动到另一个节,并在没有行时删除一个节。我正试图通过MoveRowatineXpath执行此操作,但我的代码不起作用,并引发NSRangeException异常 下面是一个代码示例: - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexP
- (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];
}
我很幸运地在moveRowAtIndexPath方法结束后的一个块中执行了deleteSections方法,方法是将删除内容包装在dispatch_async中
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];
}
你得到答案了吗。我想不出来,不太清楚。但我的解决方法如下:当用户移动行时,我不再尝试删除空节,而是在用户完成编辑后选择删除空节。然而,即使这样,删除和清空部分也不能正常工作(我怀疑是苹果的bug)。因此,为了删除空部分,我在每个空部分中添加了一行零高度,然后删除了这些部分。看看YouTube上的这个演示:看看这个方法是否适合你。