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?
Asked
Active
Viewed 3,703 times
3

Curiosity
- 544
- 1
- 15
- 29
1 Answers
9
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.

matt
- 515,959
- 87
- 875
- 1,141
-
1I tried trailingSwipeActionsConfigurationProvider, it doesn't work but leadingSwipeActionsConfigurationProvider works. it's so weird. do you have any idea – aelam Aug 25 '22 at 09:24
-
@aelam The Ask Question button is at the top right of this page. – matt Aug 25 '22 at 12:42
-
1this approach only support iOS 14 and above – JhonnyTawk Apr 19 '23 at 14:33
-
@JhonnyTawk That's right, the question was posed in 2020 and starts with the word "previously" and refers to the "new collection views". This is _exactly_ about what happens in iOS 14 and above. – matt Apr 19 '23 at 14:36
-
@matt what is the approach for iOS 13? – JhonnyTawk Apr 19 '23 at 14:39
-
@JhonnyTawk The Ask Question button is at the top right of this page. Or maybe just search? Swipe to delete has been dealt with here many, many times already. – matt Apr 19 '23 at 15:00