CollectionActionSheet.swift 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. //
  2. // CollectionActionSheet.swift
  3. // SheeeeeeeeetExample
  4. //
  5. // Created by Jonas Ullström on 2018-03-16.
  6. // Copyright © 2018 Jonas Ullström. All rights reserved.
  7. //
  8. /*
  9. This action sheet calls `setupItemsAndButtons` after it has
  10. been initialized, since taps in the collection view have to
  11. reload the action sheet to update selection display.
  12. */
  13. import Sheeeeeeeeet
  14. class CollectionActionSheet: ActionSheet {
  15. init(options: [FoodOption], action: @escaping ([MyCollectionViewCell.Item]) -> ()) {
  16. let collectionItems = CollectionActionSheet.collectionItems
  17. super.init(items: []) { _, item in
  18. guard item.isOkButton else { return }
  19. action(collectionItems.filter { $0.isSelected })
  20. }
  21. let items = self.items(for: options, collectionItems: collectionItems)
  22. setup(items: items)
  23. }
  24. required init?(coder aDecoder: NSCoder) {
  25. super.init(coder: aDecoder)
  26. }
  27. }
  28. private extension CollectionActionSheet {
  29. static var collectionItems: [MyCollectionViewCell.Item] {
  30. var items: [MyCollectionViewCell.Item] = []
  31. for i in 0...20 {
  32. items.append(MyCollectionViewCell.Item(title: "\(i)", subtitle: "\(i)"))
  33. }
  34. return items
  35. }
  36. func items(for options: [FoodOption], collectionItems: [MyCollectionViewCell.Item]) -> [ActionSheetItem] {
  37. let title = ActionSheetSectionTitle(title: ActionSheet.standardTitle, subtitle: selectionSubtitle(for: collectionItems))
  38. let setupAction = { (cell: MyCollectionViewCell, index: Int) in
  39. let item = collectionItems[index]
  40. cell.configureWith(item: item)
  41. }
  42. let selectionAction = { [weak self] (cell: MyCollectionViewCell, index: Int) in
  43. let item = collectionItems[index]
  44. item.isSelected = !item.isSelected
  45. title.subtitle = self?.selectionSubtitle(for: collectionItems)
  46. cell.configureWith(item: item)
  47. self?.reloadData()
  48. }
  49. let collectionItem = ActionSheetCollectionItem(
  50. itemCellType: MyCollectionViewCell.self,
  51. itemCount: collectionItems.count,
  52. setupAction: setupAction,
  53. selectionAction: selectionAction
  54. )
  55. return [
  56. ActionSheetSectionMargin(),
  57. title,
  58. ActionSheetSectionMargin(),
  59. collectionItem,
  60. ActionSheet.okButton,
  61. ActionSheet.cancelButton]
  62. }
  63. func selectionSubtitle(for collectionItems: [MyCollectionViewCell.Item]) -> String {
  64. return "Selected items: \(collectionItems.filter { $0.isSelected }.count)"
  65. }
  66. }