From 18fc82f037357474ca21cce5e231a7aeb40e6029 Mon Sep 17 00:00:00 2001 From: Caio Zullo Date: Wed, 20 Mar 2024 11:27:33 +0200 Subject: [PATCH] Resume shimmering animation when application re-enters foreground --- .../Views/Helpers/UIView+Shimmering.swift | 54 ++++++++++--------- 1 file changed, 30 insertions(+), 24 deletions(-) diff --git a/EssentialFeed/EssentialFeediOS/Feed UI/Views/Helpers/UIView+Shimmering.swift b/EssentialFeed/EssentialFeediOS/Feed UI/Views/Helpers/UIView+Shimmering.swift index 68630a6c..c171757b 100644 --- a/EssentialFeed/EssentialFeediOS/Feed UI/Views/Helpers/UIView+Shimmering.swift +++ b/EssentialFeed/EssentialFeediOS/Feed UI/Views/Helpers/UIView+Shimmering.swift @@ -15,37 +15,43 @@ extension UIView { } get { - return layer.mask?.animation(forKey: shimmerAnimationKey) != nil + layer.mask is ShimmeringLayer } } - private var shimmerAnimationKey: String { - return "shimmer" - } - private func startShimmering() { - let white = UIColor.white.cgColor - let alpha = UIColor.white.withAlphaComponent(0.75).cgColor - let width = bounds.width - let height = bounds.height - - let gradient = CAGradientLayer() - gradient.colors = [alpha, white, alpha] - gradient.startPoint = CGPoint(x: 0.0, y: 0.4) - gradient.endPoint = CGPoint(x: 1.0, y: 0.6) - gradient.locations = [0.4, 0.5, 0.6] - gradient.frame = CGRect(x: -width, y: 0, width: width*3, height: height) - layer.mask = gradient - - let animation = CABasicAnimation(keyPath: #keyPath(CAGradientLayer.locations)) - animation.fromValue = [0.0, 0.1, 0.2] - animation.toValue = [0.8, 0.9, 1.0] - animation.duration = 1.25 - animation.repeatCount = .infinity - gradient.add(animation, forKey: shimmerAnimationKey) + layer.mask = ShimmeringLayer(size: bounds.size) } private func stopShimmering() { layer.mask = nil } + + private class ShimmeringLayer: CAGradientLayer { + private var observer: Any? + + convenience init(size: CGSize) { + self.init() + + let white = UIColor.white.cgColor + let alpha = UIColor.white.withAlphaComponent(0.75).cgColor + + colors = [alpha, white, alpha] + startPoint = CGPoint(x: 0.0, y: 0.4) + endPoint = CGPoint(x: 1.0, y: 0.6) + locations = [0.4, 0.5, 0.6] + frame = CGRect(x: -size.width, y: 0, width: size.width*3, height: size.height) + + let animation = CABasicAnimation(keyPath: #keyPath(CAGradientLayer.locations)) + animation.fromValue = [0.0, 0.1, 0.2] + animation.toValue = [0.8, 0.9, 1.0] + animation.duration = 1.25 + animation.repeatCount = .infinity + add(animation, forKey: "shimmer") + + observer = NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: nil) { [weak self] _ in + self?.add(animation, forKey: "shimmer") + } + } + } }