UITableView中Cell的位置交换

本文详细介绍了在iOS开发中如何实现UITableView中Cell的位置交换,通过Swift代码示例解析了当选择的indexPath.row大于或小于移动到的IndexPath.row时的不同处理方式,帮助开发者理解并实现Cell的正确交换操作。

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值