Animator.swift 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2020 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import UIKit
  15. class Animator: NSObject, UIViewControllerAnimatedTransitioning {
  16. enum TransitionDirection {
  17. case right
  18. case left
  19. }
  20. let transitionDuration: Double = 0.20
  21. let transitionDirection: TransitionDirection
  22. init(_ direction: TransitionDirection) {
  23. transitionDirection = direction
  24. }
  25. func transitionDuration(using transitionContext: (any UIViewControllerContextTransitioning)?)
  26. -> TimeInterval {
  27. return transitionDuration as TimeInterval
  28. }
  29. func animateTransition(using transitionContext: any UIViewControllerContextTransitioning) {
  30. let container = transitionContext.containerView
  31. guard let fromView = transitionContext.view(forKey: .from),
  32. let toView = transitionContext.view(forKey: .to) else {
  33. transitionContext.completeTransition(false)
  34. return
  35. }
  36. let translation: CGFloat = transitionDirection == .right ? container.frame.width : -container
  37. .frame.width
  38. let toViewStartFrame = container.frame
  39. .applying(CGAffineTransform(translationX: translation, y: 0))
  40. let fromViewFinalFrame = container.frame
  41. .applying(CGAffineTransform(translationX: -translation, y: 0))
  42. container.addSubview(toView)
  43. toView.frame = toViewStartFrame
  44. UIView.animate(withDuration: transitionDuration, animations: {
  45. fromView.frame = fromViewFinalFrame
  46. toView.frame = container.frame
  47. }) { _ in
  48. fromView.removeFromSuperview()
  49. transitionContext.completeTransition(true)
  50. }
  51. }
  52. }