本文来源地址:http://www.osjoin.com
Ios中UITableview实现跨区域拖动效果的实现
在这里先复习一下Table的实现和其他的代理情况
1:在继承自UIViewController的控制器的.h文件中实现两个代理<UITableViewDataSource,UITableViewDelegate>这个代理的添加的位置不是太固定
2:实现数据源代理的中协议为@required的方法,一下必须得实现的有两个
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
这个方法是来说明每个section中对应的有多少行数据,可根据不同的section有不同的cell的行数
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
这个方法用来table实现重用池的cell复用,来定义的cell的样式等信息.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
这个方法可设置table有多个section,(默认为1)不设置默认为1
3:重重之重的是
在viewdidload的时候设置代理
self.table.dateSource = self
sel.table.delegate = self.这两个代理不设置,控制器上会一块白板
复习完成,下面来实现跨区域的拖动的效果
1:先说实现跨区域的实现的步骤
1:设置table处于编辑状态
2:设置编辑的行的状态
3:设置拖动行的交换样式
下面以这三步过程来实现程序
1:设置table处于编辑状态,通常会有一个按钮,来激发这个事件,事件的作用就是一下功能.
[self.Rview.table setEditing:!self.Rview.table.editing animated:YES];
这个特别说一下第一个参数!self.Rview.table.editing这里取反,意思就是当你点击的次数为偶数的时候会返回原有的状态
2:设置编辑的行的状态
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{
return YES;
}
这里设置的每一个cell都是位编辑状态,如果先该设置行的具体的状态,,就可以难倒indexPath.Row来具体做文章
3:设置拖动行的交换样式
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
//============1:删除开始数据中的数据=================
//去除省得名称,即事section的title的
NSString *startProName = self.province[sourceIndexPath.section];
NSMutableArray *arrys = [[NSMutableArray alloc]initWithArray:self.citys[startProName]];
NSString *cells = arrys[sourceIndexPath.row];
[arrys removeObjectAtIndex:sourceIndexPath.row];
[self.citys setObject:arrys forKey:startProName];
//==============删除开始数据中的数据结束=================
//==============2:向目标数据源中添加数据=================
//2.1 获取目标数据源的value
NSString *endProName = self.province[destinationIndexPath.section];
NSMutableArray *endarrys = [[NSMutableArray alloc]initWithArray:self.citys[endProName]];
[endarrys insertObject:cells atIndex:destinationIndexPath.row ];
[self.citys setObject:endarrys forKey:endProName];
[self.Rview.table reloadData];
}
特意的说明一下,也是本人一直调试程序的时候,老是出现”object can not nil”的错误提示了.调试了半天就是在获取cell的text的时候取值不是很准确,取值的时候不能有效取值.所有我用了
NSString *cells = arrys[sourceIndexPath.row];
最后看一下数据模式的结果
self.province = @[@"河北",@"山西",@"河南",@"广西"].mutableCopy;
NSDictionary *dict = @{
@"河北":@[@"石家庄",@"廊坊",@"赵国",@"楚襄王"], //
@"山西":@[@"太原",@"运城" ],
@"河南":@[@"济源",@"焦作",@"信阳"]
}.mutableCopy;
self.citys = [[NSMutableDictionary alloc]initWithDictionary:dict];
看一下效果
这是table加载数据的代码