1、UITableView 的编辑模式
进入编辑模式
代码体现
// 设置 editing 属性 tableView?.editing = true // 这个设置的时候是有动画效果的 tableView.setEditing(true, animated: true) // 我一般喜欢的设置方式 (写在 btn 或者 item 的监听方法里面) // 实现编辑模式和非编辑模式的切换 tableView.editing = !tableView.editing tableView.setEditing(!tableView.editing, animated: true) @IBAction func editItemAction(sender: AnyObject) { tableView.editing = !tableView.editing }
效果图
没有动画效果
有动画效果
2、 设置某一行能够进行编辑
cell 的默认编辑模式是 delete
// Individual rows can opt out of having the -editing property set for them. If not implemented, all rows are assumed to be editable. // 单行能够可选的设置编辑 1. 设置 tableView 的 editing 属性 2. 实现这个方法 // tableView 的某一行能够进行编辑模式 // 这个方法不实现,默认是每一行都进入编辑模式 optional public func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool @IBAction func editItemAction(sender: AnyObject) { tableView.setEditing(!tableView.editing, animated: true) } // 这是一个数据源方法 // 设置 tableView 那一行进入编辑模式 func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // 双数 row 行进入编辑模式 if indexPath.row % 2 == 0 { return false } return true }
3、 设置某一行编辑模式的样式
cell 编辑模式枚举 public enum UITableViewCellEditingStyle : Int { case None // 正常模式 (这一个主要用于 cell 的移动) case Delete // 删除模式 case Insert // 插入模式 } cell 编辑模式设置 // Allows customization of the editingStyle for a particular cell located at 'indexPath'. If not implemented, all editable cells will have UITableViewCellEditingStyleDelete set for them when the table has editing property set to YES. // 允许用户通过实行这个方法来自定义 cell 的编辑样式, 如果没有实现这个方法, 所有的 cell 的默认编辑样式为 UITableViewCellEditingStyleDelete . 只有 editing 属性设置为 true 的时候才可以看到效果 optional public func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle 代码 /*! 设置某一行的编辑样式 */ func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { let number = indexPath.row % 3 switch number { case 0: print("0") return UITableViewCellEditingStyle.Delete case 1: print("1") return UITableViewCellEditingStyle.Insert default: print("2") return UITableViewCellEditingStyle.None } }
效果:
上部分只是编辑样式的展示
4、 编辑模式的事件回调
@available(iOS 2.0, *) // 编辑样式 add 和 delete 附加视图点击的回调 optional public func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) 默认实现编辑事件回调方法: func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { // 没有添加任何的功能代码 } 实现这个方法后,在非编辑模式下,左滑动 cell 会显示一个 delete 按钮。
效果:
先进入了编辑模式,查看了每个 cell 的编辑模式的样式。(cell 的编辑模式的设置看上面的代码)
在非编辑模式下,只有 cell 的编辑模式是 delete 的,才可以进行左侧滑。
关于 cell 侧滑功能的实现可以先查看这段代码, 后续后详细说明!
** 事件的回调处理 **
实例代码
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAt