您的位置:首页 > 产品设计 > UI/UE

自定义拖拽cell

2016-07-06 20:34 706 查看
UITableView
自带的 move 效果需要拖特定的地方才能移动,有时并不方便。所以研究下拖任意部位拖走cell的方法



上图为一个横着的
tableView
,其中的图片可以长按之后拖走

思路为:隐藏选中的
cell
,用
UIImageView
来代替它,然后被拖来拖去。拖动的过程中如果到了一个新的位置,则更新
dataSouce
,并重新加载
tableView
,直至松手。松手后,移除替身
UIImageView
,正常显示所有的
cell
即可。

实现的步骤为:

设置一个用来保存被拖动的
cell
位置的变量
editingIndexPath
,初始为
nil
。在生产
cell
的过程中,如果
editingIndexPath
不为空,则隐藏该位置的
cell


设置一个用来保存上次手指所在位置的变量
lastIndexPath


tableView
添加
UILongPressGestureRecognizer


在手势的
state
UIGestureRecognizerStateBegan
时:(刚按下去)

使用
[recognizer locationInView:tableView];
得到按下的坐标

使用
[tableView indexPathForRowAtPoint:point];
得到该坐标所在的
indexPath


editingIndexPath
lastIndexPath
设置为
indexPath
,重新加载
tableView


得到该
cell
的快照
imageView
(本例中
cell
本身就是图片),并设置其
center


在手势的
state
UIGestureRecognizerStateChanged
时:(拖动)

获取新的坐标,设置
imageView
center
,使其实时随手移动

计算新的
indexPath
,判断是不是和
lastIndexPath
相等,如果不相等,说明图片拖到了一个新的位置,此时需要将
dataSource
中两个位置的数据进行交换,令
editingIndexPath = lastIndexPath
,并重新加载
tableView


更新
lastIndexPath


在手势的
state
UIGestureRecognizerStateEnded
时:(松手)

imageView
移除

editingIndexPath
设为
nil
,并重新加载
tableView


移动到边上
tableView
滚动、点到
headerView
上无效等等这些细节略过
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios uitableview 移动