Daniel Oram
Daniel Oram

Reputation: 8411

How to change cell editing style with animation

In the Clock app on iOS 10, toggling the cells between editing and the default style comes with a smooth animation transition (as seen in the recording below)

clock app cell style change animated

I am trying to replicate this transition for a simple app containing a tableview but I do not know how to implement the animation transition.

My app with no animation change

My app code for the editing style change is below

ViewController.swift

...

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    //Model array for cell data - omitted population of array for simplicity
    var notes = [Note]()

    //cell editing style
    var cellStyleForEditing: UITableViewCellEditingStyle = .none

    //The tableview
    @IBOutlet weak var NoteTable: UITableView!
    ...

    @IBAction func enableEdittingBttn(_ sender: AnyObject) {

        if(cellStyleForEditing == .none) {
            cellStyleForEditing = .delete
            self.NoteTable.reloadData()
        } else {
            cellStyleForEditing = .none
            self.NoteTable.reloadData()
        }
    }

    //delegate function sets cell editing style on table load/reload
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        return cellStyleForEditing
    }

    ...

    //omitted tableview delegate methods 
}

As you can see, I achieve the cell style change by reloading the table data after changing the table's cell editing style.

I have omitted all irrelevant code for simplicity.

Upvotes: 2

Views: 2918

Answers (1)

Léo Natan
Léo Natan

Reputation: 57050

Instead of reloading your table's data when enabling or disabling editing, call setEditing(_:animated:) with animated true.

if(cellStyleForEditing == .none) {
    cellStyleForEditing = .delete
} else {
    cellStyleForEditing = .none
}
NoteTable.setEditing(cellStyleForEditing != .none, animated: true)

Upvotes: 3

Related Questions