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

本文介绍如何在 iOS 应用中使用 UITableView 控件实现行的编辑与移动功能,包括设置编辑模式、实现代理方法以允许编辑和移动,并通过实例代码展示了如何更新数据源以反映视图的变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先

[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. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值