LottieAnimationViewBase.swift 1.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
//
//  LottieAnimationViewBase.swift
//  lottie-swift-iOS
//
//  Created by Brandon Withrow on 2/6/19.
//

#if canImport(UIKit)
import UIKit

/// The base view for `LottieAnimationView` on iOS, tvOS, watchOS, and macCatalyst.
///
/// Enables the `LottieAnimationView` implementation to be shared across platforms.
open class LottieAnimationViewBase: UIView {

  // MARK: Public

  public override var contentMode: UIView.ContentMode {
    didSet {
      setNeedsLayout()
    }
  }

  public override func didMoveToWindow() {
    super.didMoveToWindow()
    animationMovedToWindow()
  }

  public override func layoutSubviews() {
    super.layoutSubviews()
    layoutAnimation()
  }

  // MARK: Internal

  var viewLayer: CALayer? {
    layer
  }

  var screenScale: CGFloat {
    #if os(iOS) || os(tvOS)
    max(UITraitCollection.current.displayScale, 1)
    #else // if os(visionOS)
    // We intentionally don't check `#if os(visionOS)`, because that emits
    // a warning when building on Xcode 14 and earlier.
    1.0
    #endif
  }

  func layoutAnimation() {
    // Implemented by subclasses.
  }

  func animationMovedToWindow() {
    // Implemented by subclasses.
  }

  func commonInit() {
    contentMode = .scaleAspectFit
    clipsToBounds = true
    NotificationCenter.default.addObserver(
      self,
      selector: #selector(animationWillEnterForeground),
      name: UIApplication.willEnterForegroundNotification,
      object: nil)
    NotificationCenter.default.addObserver(
      self,
      selector: #selector(animationWillMoveToBackground),
      name: UIApplication.didEnterBackgroundNotification,
      object: nil)
  }

  @objc
  func animationWillMoveToBackground() {
    // Implemented by subclasses.
  }

  @objc
  func animationWillEnterForeground() {
    // Implemented by subclasses.
  }
}
#endif