SwipeCollectionViewCell+Accessibility.swift 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. //
  2. // SwipeCollectionViewCell+Accessibility.swift
  3. //
  4. // Created by Jeremy Koch
  5. // Copyright © 2017 Jeremy Koch. All rights reserved.
  6. //
  7. import UIKit
  8. extension SwipeCollectionViewCell {
  9. /// :nodoc:
  10. open override func accessibilityElementCount() -> Int {
  11. guard state != .center else {
  12. return super.accessibilityElementCount()
  13. }
  14. return 1
  15. }
  16. /// :nodoc:
  17. open override func accessibilityElement(at index: Int) -> Any? {
  18. guard state != .center else {
  19. return super.accessibilityElement(at: index)
  20. }
  21. return actionsView
  22. }
  23. /// :nodoc:
  24. open override func index(ofAccessibilityElement element: Any) -> Int {
  25. guard state != .center else {
  26. return super.index(ofAccessibilityElement: element)
  27. }
  28. return element is SwipeActionsView ? 0 : NSNotFound
  29. }
  30. }
  31. extension SwipeCollectionViewCell {
  32. /// :nodoc:
  33. open override var accessibilityCustomActions: [UIAccessibilityCustomAction]? {
  34. get {
  35. guard let collectionView = collectionView, let indexPath = collectionView.indexPath(for: self) else {
  36. return super.accessibilityCustomActions
  37. }
  38. let leftActions = delegate?.collectionView(collectionView, editActionsForItemAt: indexPath, for: .left) ?? []
  39. let rightActions = delegate?.collectionView(collectionView, editActionsForItemAt: indexPath, for: .right) ?? []
  40. let actions = [rightActions.first, leftActions.first].compactMap({ $0 }) + rightActions.dropFirst() + leftActions.dropFirst()
  41. if actions.count > 0 {
  42. return actions.compactMap({ SwipeAccessibilityCustomAction(action: $0,
  43. indexPath: indexPath,
  44. target: self,
  45. selector: #selector(performAccessibilityCustomAction(accessibilityCustomAction:))) })
  46. } else {
  47. return super.accessibilityCustomActions
  48. }
  49. }
  50. set {
  51. super.accessibilityCustomActions = newValue
  52. }
  53. }
  54. @objc func performAccessibilityCustomAction(accessibilityCustomAction: SwipeAccessibilityCustomAction) -> Bool {
  55. guard let collectionView = collectionView else { return false }
  56. let swipeAction = accessibilityCustomAction.action
  57. swipeAction.handler?(swipeAction, accessibilityCustomAction.indexPath)
  58. if swipeAction.style == .destructive {
  59. collectionView.deleteItems(at: [accessibilityCustomAction.indexPath])
  60. }
  61. return true
  62. }
  63. }