UItableView 如何实现Cell之间交换位置

时间:2022-09-25 15:48:05
首先

[self.tableViewsetEditing:YESanimated:YES]; 打开UItableView 的编辑模式


然后 实现两个代理方法:

-(BOOL)tableView:(UITableView *) tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

{

    //打开编辑

    return YES;

}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath

{

    //允许移动

    return YES;

    //return NO;

}

最后实现代理方法

-(void) tableView: (UITableView *) tableView moveRowAtIndexPath: (NSIndexPath *) oldPath toIndexPath:(NSIndexPath *) newPath
{
// NSString *title = [[self.categoryList objectAtIndex:oldPath.row] retain];
BookCategory * caterory = [[self.categoryList objectAtIndex:oldPath.row] retain];
NSLog(@"title is %@",caterory);
[self.categoryList removeObjectAtIndex:oldPath.row];
[self.categoryList insertObject:caterory atIndex:newPath.row];
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
for(int i=0;i<[self.categoryList count];i++){
BookCategory *bc = [self.categoryList objectAtIndex:i];
NSString *key = bc.categoryId;
NSInteger index = [self.categoryList indexOfObject:bc];
NSNumber *value = [NSNumber numberWithInt:index];
[ud setObject:value forKey:key];
}
[caterory release];
[self.tableView reloadData];
}