/**侧滑删除实现的三个方法: * canEditRowAt :设为true 才能侧滑或其他操作 * editActionsForRowAt (11之前侧滑删除) * trailingSwipeActionsConfigurationForRowAt (11之后的侧滑删除) */ //canEditRowAt :设为true 才能侧滑或其他操作 @objc optional func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool /// 11之前侧滑删除 @objc optional func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? ///11之后的侧滑删除 @available(iOS 11.0, *) @objc optional func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
func tableViewl(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { //显示/隐藏 let showStateAction = UITableViewRowAction.init(style: .default, title: showStateTitle) { [weak self] (res, index) in } } showStateAction.backgroundColor = UIColor.red //1删除 let deleteAction = UITableViewRowAction(style: UITableViewRowAction.Style.default, title: "删除") { [weak self] (res, index) in } deleteAction.backgroundColor = UIColor.green return [showStateAction, deleteAction] }
在iOS11之后多了一个方法,并且 侧滑会直接 左滑到底, 造成误删除, 需要禁用
UISwipeActionsConfiguration的performsFirstActionWithFullSwipe 属性,改为false
//尾部滑动事件按钮(左滑按钮) @available(iOS 11.0, *) func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let showStateAction = UIContextualAction(style: UIContextualAction.Style.destructive, title: "文字") { [weak self](action:UIContextualAction, view:UIView, handle:@escaping (Bool) -> Void) in } showStateAction.backgroundColor = UIColor.init(hexString: "#D1D1D1") //删除 let deleteAction = UIContextualAction(style: UIContextualAction.Style.destructive, title: "删除") { [weak self](acction:UIContextualAction, view:UIView, handle:@escaping (Bool) -> Void) in } deleteAction.backgroundColor = UIColor.init(hexString: "#F53943") //destructive图片 let destructiveImageAction = UIContextualAction(style: UIContextualAction.Style.destructive, title: nil) { [weak self](acction:UIContextualAction, view:UIView, handle:@escaping (Bool) -> Void) in self?.deleteOrder(by: indexPath.section) } if let ima = UIImage.init(named: "tempOrderDelete"){ ///设置图片 destructiveImageAction.image = ima ///和cell背景色一样就可以 destructiveImageAction.backgroundColor = UIColor.init(red: 195, green: 76, blue: 93, alpha: 1) } let configuration = UISwipeActionsConfiguration(actions: [showStateAction, deleteAction, destructiveImageAction]) configuration.performsFirstActionWithFullSwipe = false return configuration }
参考:
Swift - 自定义tableViewCell滑动事件按钮2(使用iOS11的滑动按钮接口)
https://www.hangge.com/blog/cache/detail_1891.html