Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableViewDiffableDataSource set different cell animations

I'm using UITableViewDiffableDataSource to render cells, and I wonder how to animate rows granularily.

There's a property

self.dataSource?.defaultRowAnimation = .fade

which apply for all rows of the tableView, but I would like some animation for certain cells, and NO animation for others. The "default" in "defaultRowAnimation" suggest there are other methods.

Unfortunately, Apple documentation on the subjet is a bit light

Is there a method that asks a RowAnimation according to the given IndexPath for example?

like image 392
Martin Avatar asked Sep 13 '25 14:09

Martin


1 Answers

Unfortunately there isn't a delegate method or similar that asks you which animation to use for which cell, however in UITableViewDiffableDataSource.update(sections:) you can choose which animation to use based on any criteria you like as long as its represented in the model. E.g.


class MyTableViewDataSource: UITableViewDiffableDataSource<ListSectionID, ListItemID> {

func update(animated: Bool = true) {
    var newSnapshot = NSDiffableDataSourceSnapshot<ListSectionID, ListItemID>()
    newSnapshot.appendSections([.theSection])

    if let items = DataManager.shared.itemsUsingFadeAnimation {
        let ids = items.map { ListItemID(id: $0.id) }
        newSnapshot.appendItems(items, toSection: .theSection)
        .defaultRowAnimation = .fade
        apply(newSnapshot, animatingDifferences: animated)
    }
    if let items = DataManager.shared.itemsUsingMiddleAnimation {
        let ids = items.map { ListItemID(id: $0.id) }
        // insert these ids into the snapshot using `appendItems` or `insertItems`
        .defaultRowAnimation = .middle
        apply(newSnapshot, animatingDifferences: animated)
    }

}
like image 137
John Scalo Avatar answered Sep 15 '25 12:09

John Scalo