Curiosity
Curiosity

Reputation: 264

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

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?

Upvotes: 4

Views: 5403

Answers (1)

matt
matt

Reputation: 535831

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.

Upvotes: 11

Related Questions