JXSegmentedAnimator.swift 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. //
  2. // JXSegmentedAnimator.swift
  3. // JXSegmentedView
  4. //
  5. // Created by jiaxin on 2019/1/21.
  6. // Copyright © 2019 jiaxin. All rights reserved.
  7. //
  8. import Foundation
  9. import UIKit
  10. open class JXSegmentedAnimator {
  11. open var duration: TimeInterval = 0.25
  12. open var progressClosure: ((CGFloat)->())?
  13. open var completedClosure: (()->())?
  14. private var displayLink: CADisplayLink!
  15. private var firstTimestamp: CFTimeInterval?
  16. deinit {
  17. progressClosure = nil
  18. completedClosure = nil
  19. }
  20. public init() {
  21. displayLink = CADisplayLink(target: self, selector: #selector(processDisplayLink(sender:)))
  22. }
  23. open func start() {
  24. displayLink.add(to: RunLoop.main, forMode: RunLoop.Mode.common)
  25. }
  26. open func stop() {
  27. progressClosure?(1)
  28. displayLink.invalidate()
  29. completedClosure?()
  30. }
  31. @objc private func processDisplayLink(sender: CADisplayLink) {
  32. if firstTimestamp == nil {
  33. firstTimestamp = sender.timestamp
  34. }
  35. let percent = (sender.timestamp - firstTimestamp!)/duration
  36. if percent >= 1 {
  37. progressClosure?(1)
  38. displayLink.invalidate()
  39. completedClosure?()
  40. }else {
  41. progressClosure?(CGFloat(percent))
  42. }
  43. }
  44. }