Home > Software design >  How to set a UITableView Editing Mode from a swipe action?
How to set a UITableView Editing Mode from a swipe action?

Time:02-14

I need to turn on a tableView editing mode by clicking on one of its cells from swipe action "move":

Code for swipe action:

override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let move = UIContextualAction(style: .normal, title: "Переместить") { (action, view, completionHandler) in
        self.turnEditing()
        completionHandler(true)
    }
    move.backgroundColor = UIColor(named: "CalmBlueColor")
    
    let configuration = UISwipeActionsConfiguration(actions: [move])
    return configuration
}

turnEditing() function:

   func turnEditing() {
       if tableView.isEditing {
           tableView.isEditing = false
       } else {
           tableView.isEditing = true
       }
    }

TableView Delegates:

 override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    return true
}

override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    
}

override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
    return .none
}

override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
    return false
}

When I press on the swipe actions it's just closes, without going to editing mode... Here is the GIF

Is it possible to go into editing mode from a swipe action or only from a barButtonItem IBAction?

CodePudding user response:

Add some delay

DispatchQueue.main.asyncAfter(deadline: .now()   0.75) {
  self.turnEditing()
}

BTW you could replace this

if tableView.isEditing {
  tableView.isEditing = false
} else {
  tableView.isEditing = true
}

With

tableView.isEditing.toggle()
  • Related