Last active
March 5, 2019 19:21
-
-
Save IsaiasSantana/420f2a9b36d0d469a222c0773fcac7e2 to your computer and use it in GitHub Desktop.
Simple shimmer effect into uiview
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| extension UIView { | |
| private enum ShimmerViews: Int { | |
| case backgroundView = 1234 | |
| case shimmerView = 123 | |
| } | |
| func startShimmer() { | |
| func createUIView(withTag tag: ShimmerViews, backgroundColor color: UIColor) -> UIView { | |
| let view = UIView(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height)) | |
| view.tag = tag.rawValue | |
| view.backgroundColor = color | |
| return view | |
| } | |
| func setShimmerEffectInto(view shimmerView: UIView) { | |
| let gradientLayer = CAGradientLayer() | |
| gradientLayer.colors = [UIColor.clear.cgColor, UIColor.white.withAlphaComponent(0.8).cgColor, UIColor.clear.cgColor] | |
| gradientLayer.startPoint = CGPoint(x: 0.7, y: 1.0) | |
| gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.8) | |
| gradientLayer.frame = shimmerView.bounds | |
| shimmerView.layer.mask = gradientLayer | |
| let animation = CABasicAnimation(keyPath: "transform.translation.x") | |
| animation.duration = 1.5 | |
| animation.fromValue = -shimmerView.frame.width | |
| animation.toValue = shimmerView.frame.width | |
| animation.repeatCount = .infinity | |
| gradientLayer.add(animation, forKey: "") | |
| } | |
| let shimmerView = createUIView(withTag: .shimmerView, backgroundColor: .white) | |
| let backgroundView = createUIView(withTag: .backgroundView, backgroundColor: .gray) | |
| addSubview(backgroundView) | |
| addSubview(shimmerView) | |
| shimmerView.clipsToBounds = true | |
| backgroundView.clipsToBounds = true | |
| setShimmerEffectInto(view: shimmerView) | |
| } | |
| func stopShimmer() { | |
| viewWithTag(ShimmerViews.backgroundView.rawValue)?.removeFromSuperview() | |
| viewWithTag(ShimmerViews.shimmerView.rawValue)?.removeFromSuperview() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment