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

来源:互联网 发布:强力安卓数据恢复精灵 编辑:程序博客网 时间:2024/05/16 17:20
首先

[self.tableView setEditing:YES animated:YES]; 打开UItableView 的编辑模式


然后 实现两个代理方法:

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

{

    //打开编辑

    return YES;

}

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

{

    //允许移动

    return YES;

    //return NO;

}

最后实现代理方法

[cpp] view plain copy
  1. -(void) tableView: (UITableView *) tableView moveRowAtIndexPath: (NSIndexPath *) oldPath toIndexPath:(NSIndexPath *) newPath  
  2. {  
  3.    // NSString *title = [[self.categoryList objectAtIndex:oldPath.row] retain];  
  4.     BookCategory * caterory = [[self.categoryList objectAtIndex:oldPath.row] retain];  
  5.     NSLog(@"title is %@",caterory);  
  6.     [self.categoryList removeObjectAtIndex:oldPath.row];  
  7.     [self.categoryList insertObject:caterory atIndex:newPath.row];  
  8.     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];  
  9.     for(int i=0;i<[self.categoryList count];i++){  
  10.         BookCategory *bc = [self.categoryList objectAtIndex:i];  
  11.         NSString *key = bc.categoryId;  
  12.         NSInteger index = [self.categoryList indexOfObject:bc];  
  13.         NSNumber *value = [NSNumber numberWithInt:index];  
  14.         [ud setObject:value forKey:key];  
  15.     }  
  16.     [caterory release];  
  17.     [self.tableView reloadData];  
  18. }