UITableView中Cell的位置交换
2015-07-29 20:51
549 查看
cell的位置交换
先上代码:/// Move Cell override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { LOG("star:\(sourceIndexPath.row) end:\(destinationIndexPath.row)") let bk = bookmark[sourceIndexPath.row] if sourceIndexPath.row > destinationIndexPath.row { realm.write { self.bookmark.insert(bk, atIndex: destinationIndexPath.row) self.bookmark.removeAtIndex(sourceIndexPath.row + 1) } } else if sourceIndexPath.row < destinationIndexPath.row { realm.write { self.bookmark.insert(bk, atIndex: destinationIndexPath.row + 1) self.bookmark.removeAtIndex(sourceIndexPath.row) } } }
/// Can Move Cell override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } /// Can Edit Cell override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true }
首先,实现上面3个代理方法
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath)
func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool然后,拿到当前选中的元素,或者叫数据都可以,这个元素是根据当前的indexPath.row在数组中拿到的。
拿到之后,开始对其进行判断比较。
如果当前选中的indexPath.row 大于 移动到的IndexPath.row 的话,则在数组中的destinationIndexPath.row的位置插入选中的元素,删除sourceIndexPath.row + 1 位置上的元素。
这里可能有点绕,举个例子:
数组:[a,b,c,d,e,f];
选中的数据保存到tmp中:tmp = c 也就是说,我们现在选中的是c并且开始选中的位置是2;
然后我们把它移动到:a的位置,也就是说移动到的indexpath.row是0;
这里的伪代码就是:开始位置 > 移动后位置 { 将tmp的数据插入移动后的位置0;删除开始选中位置 + 1 的数据 };
插入后数组样式:【c,a,b,c,d,e,f】我们在0的位置插入了蓝色的c,这个时候数组中就会有2个c,我们必须将红色的c删除;
删除的时候必须在之前2的基础上+1才可以正确的拿到要删除的元素 【c,a,b,c,d,e,f】,因为此时红色的c的游标是3;
同理
如果当前选中的indexPath.row 小于 移动到的IndexPath.row 的话,则在数组中的destinationIndexPath.row + 1 的位置插入选中的元素,删除sourceIndexPath.row 位置上的元素。
数组:[a,b,c,d,e,f];
选中的数据保存到tmp中:tmp = b 现在选中的是b并且开始选中的位置是1;
然后我们把它移动到:e的位置,也就是说移动到的indexpath.row是4;
这里的伪代码就是:开始位置 < 移动后位置 { 将tmp的数据插入移动后的位置4+1;删除1 位置的数据 };
插入后数组样式:【a,b,c,d,e,b,f】我们在4+1的位置插入了蓝色的b,这个时候数组中就会有2个b,我们必须将红色的b删除;
以上就是cell交换位置的说明,希望可以帮到正在看这篇文章的朋友
相关文章推荐
- 60. Permutation Sequence
- UIView的layoutSubviews和drawRect方法何时调用
- 经典中的经典Unique Binary Search Trees II
- hdoj-1159-Common Subsequence【动态规划求最长公共子序列】
- 利用UIView做出霓虹灯的效果
- 求逆序对——Ultra-QuickSort 题解解析
- UIView
- IOS开发之UITableView1
- Snail—UI学习之系统标签栏UITabBarController
- POJ 1679 The Unique MST
- ios UI 适配布局相关文章
- CodeForces 5C Longest Regular Bracket Sequence
- Beginners Guide To Learn Dimension Reduction Techniques
- UI02_Label
- ExQuilla的使用和破解
- StringBuffer 与 StringBuilder类的使用
- Android API Guides 阅读笔记(7)----Overview Screen
- request.getParameterMap()的用法
- UI 第三课 ⼀、自定义视图 二、视图控制器指定⾃自定义View 三、检测屏幕旋转 四、处理内存警告 五、容器视图控制器
- iOS -UI-06 UIImageView 动画