Skip to content

Instantly share code, notes, and snippets.

@policante
Created February 6, 2017 14:09
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save policante/2e45915e8077635fcb7826958c4aa7bd to your computer and use it in GitHub Desktop.
Save policante/2e45915e8077635fcb7826958c4aa7bd to your computer and use it in GitHub Desktop.
Shimmer effect to UIView
extension UIView {
func startShimmering(){
let light = UIColor.white.cgColor
let alpha = UIColor.white.withAlphaComponent(0.7).cgColor
let gradient = CAGradientLayer()
gradient.colors = [alpha, light, alpha, alpha, light, alpha]
gradient.frame = CGRect(x: -self.bounds.size.width, y: 0, width: 3 * self.bounds.size.width, height: self.bounds.size.height)
gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
gradient.endPoint = CGPoint(x: 1.0, y: 0.525)
gradient.locations = [0.4, 0.5, 0.6]
self.layer.mask = gradient
let animation = CABasicAnimation(keyPath: "locations")
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
}
}
@LordOfTheRains
Copy link

Hi I'm trying to implement this to my tableview cells. basically calling start shimmer on custom cells label and image views inside cell for row at index function, but nothing is working, can you give an example on how to use this extension?

@policante
Copy link
Author

Hello, I have not used this extension in TableView. I used it in an ImageView.
See this library for help:
https://github.com/malkouz/ListPlaceholder

@gali8
Copy link

gali8 commented Sep 11, 2018

Works using gradient.colors = [alpha, light, alpha]

@riyanpratamap
Copy link

it doesnt work at presented modally viewcontroller, why?

@akun1
Copy link

akun1 commented Jul 12, 2019

@gali8 Worked! Thanks!

@hritik1998
Copy link

it work with uitableView as well..
gradient.frame = CGRect(x: -self.bounds.size.width, y: 0, width: 3 * self.bounds.size.width, height: self.bounds.size.height)

sometimes when you create your cell using code this line will not work because UIElements do not get frame initially.. please use

gradient.frame = CGRect(x: 0, y: 0, width: (UIScreen.main.bounds.width), height: some static value )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment