You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现UITableViewCell拖动侧滑后松手自动回归初始位置?

解决UITableViewCell侧滑后松手不自动复位的问题

嘿,我太懂你遇到的这个小麻烦了!其实问题根源就在一个容易被忽略的属性上,咱们稍微调整一下代码就能搞定。

默认情况下,UISwipeActionsConfiguration的performsFirstActionWithFullSwipe属性是true,这会带来两个行为:

  • 当你完全滑过单元格时,会自动触发第一个侧滑动作
  • 但如果只是滑到一半就松手,单元格会停留在当前位置,必须点击才会复位

要实现“松手自动回归初始位置”,只需要把这个属性设置为false即可。这样不管你滑到什么程度,只要松手,单元格都会立即弹回去,只有点击侧滑出来的按钮才会执行对应的操作。

修改后的完整代码如下:

override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { 
    let closeAction = UIContextualAction(style: .normal, title: "Close", handler: { (ac:UIContextualAction, view: UIView, success:(Bool) -> Void) in 
        success(true) 
    }) 
    closeAction.image = UIImage(named: "tick") 
    closeAction.backgroundColor = .purple 
    let config = UISwipeActionsConfiguration(actions: [closeAction])
    // 添加这一行,关闭全滑自动触发,松手即复位
    config.performsFirstActionWithFullSwipe = false
    return config 
} 

override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { 
    let modifyAction = UIContextualAction(style: .normal, title: "Update", handler: { (ac:UIContextualAction, view: UIView, success:(Bool) -> Void) in 
        print("Update action ...") 
        success(true) 
    }) 
    modifyAction.image = UIImage(named: "hammer") 
    modifyAction.backgroundColor = .blue 
    let config = UISwipeActionsConfiguration(actions: [modifyAction])
    // 同样添加这一行
    config.performsFirstActionWithFullSwipe = false
    return config 
}

现在再去测试侧滑:拖动单元格到任意位置松手,它都会乖乖回到初始状态,完全符合你的需求~

内容的提问来源于stack exchange,提问作者Suren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:10:56