How do you support swiping to delete a row in a UICollectionView list with compositional layout?

4.5k views Asked by At

Previously with table views this was done in the UITableViewDataSource delegate callback tableView(_:commit:forRowAt:). Is there equivalent functionality in the APIs associated with the new collection views, or a recommended way of implementing it?

1

There are 1 answers

6
matt On BEST ANSWER

The UICollectionLayoutListConfiguration, which you used to create the layout, has leadingSwipeActionsConfigurationProvider and trailingSwipeActionsConfigurationProvider properties that are functions taking an index path. Your function can return different swipe actions, or nil, for different rows of the list:

var config = UICollectionLayoutListConfiguration(appearance: .plain)
config.trailingSwipeActionsConfigurationProvider = { indexPath in
    let del = UIContextualAction(style: .destructive, title: "Delete") {
        [weak self] action, view, completion in
        self?.delete(at: indexPath)
        completion(true)
    }
    return UISwipeActionsConfiguration(actions: [del])
}

Writing delete(at:) is left as an exercise for the reader; basically you just do the very same thing you would have done in any collection view.