Extensions.swift 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. //
  2. // Extensions.swift
  3. //
  4. // Created by Jeremy Koch
  5. // Copyright © 2017 Jeremy Koch. All rights reserved.
  6. //
  7. import UIKit
  8. extension UITableView {
  9. var swipeCells: [SwipeTableViewCell] {
  10. return visibleCells.compactMap({ $0 as? SwipeTableViewCell })
  11. }
  12. func hideSwipeCell() {
  13. swipeCells.forEach { $0.hideSwipe(animated: true) }
  14. }
  15. }
  16. extension UICollectionView {
  17. var swipeCells: [SwipeCollectionViewCell] {
  18. return visibleCells.compactMap({ $0 as? SwipeCollectionViewCell })
  19. }
  20. func hideSwipeCell() {
  21. swipeCells.forEach { $0.hideSwipe(animated: true) }
  22. }
  23. func setGestureEnabled(_ enabled: Bool) {
  24. gestureRecognizers?.forEach {
  25. guard $0 != panGestureRecognizer else { return }
  26. $0.isEnabled = enabled
  27. }
  28. }
  29. }
  30. extension UIScrollView {
  31. var swipeables: [Swipeable] {
  32. switch self {
  33. case let tableView as UITableView:
  34. return tableView.swipeCells
  35. case let collectionView as UICollectionView:
  36. return collectionView.swipeCells
  37. default:
  38. return []
  39. }
  40. }
  41. func hideSwipeables() {
  42. switch self {
  43. case let tableView as UITableView:
  44. tableView.hideSwipeCell()
  45. case let collectionView as UICollectionView:
  46. collectionView.hideSwipeCell()
  47. default:
  48. return
  49. }
  50. }
  51. }
  52. extension UIPanGestureRecognizer {
  53. func elasticTranslation(in view: UIView?, withLimit limit: CGSize, fromOriginalCenter center: CGPoint, applyingRatio ratio: CGFloat = 0.20) -> CGPoint {
  54. let translation = self.translation(in: view)
  55. guard let sourceView = self.view else {
  56. return translation
  57. }
  58. let updatedCenter = CGPoint(x: center.x + translation.x, y: center.y + translation.y)
  59. let distanceFromCenter = CGSize(width: abs(updatedCenter.x - sourceView.bounds.midX),
  60. height: abs(updatedCenter.y - sourceView.bounds.midY))
  61. let inverseRatio = 1.0 - ratio
  62. let scale: (x: CGFloat, y: CGFloat) = (updatedCenter.x < sourceView.bounds.midX ? -1 : 1, updatedCenter.y < sourceView.bounds.midY ? -1 : 1)
  63. let x = updatedCenter.x - (distanceFromCenter.width > limit.width ? inverseRatio * (distanceFromCenter.width - limit.width) * scale.x : 0)
  64. let y = updatedCenter.y - (distanceFromCenter.height > limit.height ? inverseRatio * (distanceFromCenter.height - limit.height) * scale.y : 0)
  65. return CGPoint(x: x, y: y)
  66. }
  67. }