Skip to content

Instantly share code, notes, and snippets.

@NeilsUltimateLab
Created June 16, 2018 05:27
Show Gist options
  • Save NeilsUltimateLab/1b4acb1de19bf32f7c025f92e4748b5e to your computer and use it in GitHub Desktop.
Save NeilsUltimateLab/1b4acb1de19bf32f7c025f92e4748b5e to your computer and use it in GitHub Desktop.
UIView shimmering effect

Shimmering Effect

import UIKit

extension UIView {
  func startShimmering() {
    let light = self.tintColor.cgColor
    let dark = UIColor(white: 0, alpha: 0.3).cgColor

    let gradient = CAGradientLayer()
    gradient.colors = [light, dark, light]
    gradient.frame = CGRect(x: -self.bounds.size.width, y: 0, width: 3 * self.bounds.width, height: self.bounds.height)
    gradient.location = [0.4, 0.5, 0.6]
    self.layer.mask = gradient

    let animation = CABasicAnimation(keyPath: "location")
    animation.fromValue = [0.0, 0.1, 0.2]
    animation.toValue = [0.8, 0.9, 1.0]

    animation.duration = 1.5
    animation.repeatCount = HUGE

    gradient.add(animation, forKey: "shimmer")
  }

  func stopShimmering() {
    self.layer.mask = nil
  }

  func resumeShimmering() {
    guard let gradientMask = self.layer.mask as? CAGradientLayer else { return }
    gradientMask.removeAnimation(forKey: "shimmer")
    self.startShimmering()
  }
  
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment