返回
实现 UITableViewCell 侧滑操作列表
IOS
2023-09-19 19:43:07
对于一个程序员来说,所掌握的工具和知识是我们的吃饭家伙。但是在工作中有些时候会遇到一些比较繁琐或者容易出错的地方,比如 UITableViewCell 侧滑删除操作。虽然我们可以通过实现三个代理方法来完成这个功能,但是未免有点繁琐。实际上,我们可以通过一种更简单的方式来实现这个功能。
首先,我们需要在 tableView 的 cellForRowAtIndexPath 方法中设置 cell 的编辑样式。我们可以通过调用 cell.editingStyle = UITableViewCellEditingStyle.delete 来设置 cell 的编辑样式为删除样式。这样,当用户在 cell 上向左滑动时,就会出现一个红色的删除按钮。
然后,我们需要在 tableView 的 commitEditingStyle 方法中处理用户的编辑操作。我们可以通过调用 tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: .fade) 来删除选中的行。
最后,我们可以通过重写 tableView 的 titleForDeleteConfirmationButton 方法来自定义删除确认按钮的标题。我们可以通过返回一个字符串来设置删除确认按钮的标题。
下面是一个简单的示例代码,演示了如何实现 UITableViewCell 侧滑删除操作:
// 在 cellForRowAtIndexPath 方法中设置 cell 的编辑样式
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.editingStyle = .Delete
return cell
}
// 在 commitEditingStyle 方法中处理用户的编辑操作
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
// 在 titleForDeleteConfirmationButton 方法中自定义删除确认按钮的标题
func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? {
return "删除"
}
通过这种方式,我们就可以轻松地实现 UITableViewCell 侧滑删除操作。