UITableView中Cell的位置交换

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交换位置的说明,希望可以帮到正在看这篇文章的朋友


版权声明:本文为gygh123原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。