Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calvingit/442dde5075edf5a6f0e51da5ded2c352 to your computer and use it in GitHub Desktop.
Save calvingit/442dde5075edf5a6f0e51da5ded2c352 to your computer and use it in GitHub Desktop.

1. UITableView 在编辑模式下可以实现默认的排序功能

    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
        tableView.moveRow(at: fromIndexPath, to: to)
    }
       
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        true
    }

2. UITableView 在非编辑模式下,可以实现左滑删除功能

    override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { (action, view, completionHandler) in
//            // 删除数据
//            self?.data.remove(at: indexPath.row)
//
            // 删除行
            tableView.deleteRows(at: [indexPath], with: .fade)
            
            completionHandler(true)
        }
        
        let swipeConfig = UISwipeActionsConfiguration(actions: [deleteAction])
        swipeConfig.performsFirstActionWithFullSwipe = true
        
        return swipeConfig
    }

3. 但是这两者不能共存,即编辑模式下,左滑失效了。 当你想要排序和左滑删除功能,又不想要编辑模式下的左边红色减号按钮,就只能想办法自己实现排序功能了。 好在iOS 11 之后有了新的Drag And Drop 功能:

tableView.dragInteractionEnabled = true
tableView.dragDelegate = self
tableView.dropDelegate = self

具体实现查看:https://developer.apple.com/documentation/uikit/drag_and_drop/adopting_drag_and_drop_in_a_table_view

或者参考:

4. 其他

  • SwipeCellKit: 专门用于左右滑动的菜单,但是在UITableView 为 insetGroup 时有一个崩溃 bug
  • LPRTableView:长按排序功能
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment