NetAnimationLoadable.swift 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //
  2. // NetAnimationLoadable.swift
  3. // SwiftBilibili
  4. //
  5. // Created by 罗文 on 2021/1/15.
  6. // Copyright © 2021年 罗文. All rights reserved.
  7. //
  8. import UIKit
  9. private var animationKey: Void?
  10. protocol NetAnimationLoadable {}
  11. extension NetAnimationLoadable where Self: UIViewController {
  12. private var animationType: AnimationType? {
  13. get { return objc_getAssociatedObject(self, &animationKey) as? AnimationType }
  14. set { objc_setAssociatedObject(self, &animationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
  15. }
  16. func showAnimationView(_ superView:UIView,animationType:AnimationType = .loading) {
  17. let insert = self
  18. if insert.animationType == animationType { return }
  19. if let existView = superView.subviews.filter({ $0.isKind(of: NetAnimationView.self) }).first as? NetAnimationView {
  20. existView.removeFromSuperview()
  21. }
  22. insert.animationType = animationType
  23. let animationView = NetAnimationView(animationType: animationType)
  24. superView.addSubview(animationView)
  25. superView.bringSubviewToFront(animationView)
  26. animationView.snp.makeConstraints { (make) in
  27. make.width.equalTo(200)
  28. make.height.equalTo(220)
  29. make.centerX.equalToSuperview()
  30. make.centerY.equalTo(superView).offset(-50*kScreenRatio)
  31. }
  32. animationView.startAnimation(animationType:animationType)
  33. }
  34. func hideAnimationView(_ superView:UIView) {
  35. guard let animationView = superView.subviews.filter({ $0.isKind(of: NetAnimationView.self) }).first as? NetAnimationView else { return }
  36. let insert = self
  37. animationView.stopAnimation(animationType:insert.animationType!)
  38. insert.animationType = nil
  39. animationView.removeFromSuperview()
  40. }
  41. }