UIScrollView+Direction.swift 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //
  2. // UIScrollView+Direction.swift
  3. // SwiftBilibili
  4. //
  5. // Created by 罗文 on 2021/6/21.
  6. // Copyright © 2021年 罗文. All rights reserved.
  7. //
  8. import UIKit
  9. import RxSwift
  10. enum ScrollDirection {
  11. case none
  12. case down
  13. case up
  14. }
  15. extension UIScrollView {
  16. private struct AssociatedKeys {
  17. static var scrollDirection = "scrollDirection"
  18. static var enableDirection = "enableDirection"
  19. }
  20. var scrollDirection: ScrollDirection {
  21. get {
  22. return objc_getAssociatedObject(self, &AssociatedKeys.scrollDirection) as? ScrollDirection ?? .none
  23. }
  24. set {
  25. objc_setAssociatedObject(self, &AssociatedKeys.scrollDirection, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  26. }
  27. }
  28. var enableDirection: Bool {
  29. get {
  30. return objc_getAssociatedObject(self, &AssociatedKeys.enableDirection) as? Bool ?? false
  31. }
  32. set {
  33. objc_setAssociatedObject(self, &AssociatedKeys.enableDirection, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  34. if enableDirection {
  35. self.addObserver(self, forKeyPath: "contentOffest", options: [.old,.new], context: nil)
  36. }
  37. }
  38. }
  39. override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
  40. if keyPath == "contentOffest" {
  41. let newOffest = change?[NSKeyValueChangeKey.newKey] as? CGPoint ?? .zero
  42. let oldOffest = change?[NSKeyValueChangeKey.oldKey] as? CGPoint ?? .zero
  43. if newOffest.y > oldOffest.y {
  44. self.scrollDirection = .up
  45. }else if newOffest.y < oldOffest.y {
  46. self.scrollDirection = .down
  47. }
  48. }
  49. }
  50. }