# UIButton subclass with animated 'shimmer' effect

In earlier versions of iOS the lock screen had a 'slide to unlock' element which I'm referencing as a 'shimmer' effect.

The effect I'm looking for is simpler:

1. Button starts with single color (e.g. blue)
2. a band of color (e.g. red) sweeps across the text label from left to right
3. Repeat

Here's an example of my ShimmerButton class in action, and the code itself:

class ShimmerButton: UIButton {

private let wrapperLayer = CALayer()

var gradientColors: [UIColor] = [] {
didSet {
}
}

override func layoutSubviews() {
super.layoutSubviews()

// only needs to be set once, but no harm (?) in setting multiple times
gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
layer.insertSublayer(wrapperLayer, at: 0)

// update sublayers based on new frame
wrapperLayer.frame = frame
gradientLayer.frame.size = CGSize(width: frame.width * 4, height: frame.height)

// remove any existing animation, and re-create for new size
let animationKeyPath = "position.x"

let animation: CABasicAnimation = CABasicAnimation(keyPath: animationKeyPath)

animation.fromValue = bounds.width - gradientLayer.bounds.width / 2
animation.duration = 3

animation.repeatCount = HUGE
animation.fillMode = kCAFillModeForwards
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)

}
}


Example usage:

let shimmer = ShimmerButton(frame: .zero)
shimmer.backgroundColor = .white
shimmer.setTitle("Find new skills...", for: .normal)
shimmer.titleLabel?.font = UIFont.systemFont(ofSize: 24, weight: UIFontWeightHeavy)
shimmer.sizeToFit()
shimmer.gradientColors = [.blue, .blue, .red, .blue, .blue]


Some questions:

1. Code that only needs to be once off is happening in layoutSubviews so will be called multiple times. I did this so I didn't have to override init?(coder:) and init(frame:). Is this acceptable, or just lazy on my part?
2. I'm animating the position of a CAGradientLayer to get the visual effect, but found that I needed to use another layer as a wrapper otherwise the text itself would move. Am I overlooking a solution that involves fewer layers?

Okay, so sometimes posting a question is the best way to figure out an answer yourself 🙃.

I was looking for an alternative to having the gradient colors evenly spaced (my hack was to repeat the colors e.g. "blue blue red blue blue") and found the locations property on CAGradientLayer which is also animatable.

Animating this property feels like a much better approach because with the position not changing I can remove the wrapper layer.

Then, with without the wrapper layer I realized that I could override layerClass so the buttons backing layer is a gradient layer, which will also resize as needed when the view frame changes so that I don't even need to override layoutSubviews.

The only thing that feels a little strange is the forced requirement for for gradient colors to have three colors (otherwise I'd need to figure some formula to derive values for locations).

Edit: I've updated answer so instead of directly setting the colors, I've exposed gradientTint and gradientHighlight properties that are used to set the gradients colors array.

I've created a protocol that captures the properties used to define the shimmer effect, and also provide a default implementation of the animation.

It wasn't a requirement from my original question, but moving this code out of a specific subclass makes this snippet of code reusable (and maintainable) across other subclasses (e.g. UIView, UILabel).

protocol ShimmerEffect {
var animationDuration: TimeInterval { set get }
var animationDelay: TimeInterval {set get }

var gradientTint: UIColor { set get }
var gradientHighlight: UIColor { set get }

//// Expects value between 0.0—1.0 that represents
//// the ratio of the gradient highlight to the full
var gradientHighlightRatio: Double { set get }

//// The layer that the gradient will be applied to
}


Default implementation:

extension ShimmerEffect {

// gradientHighlightRatio represents how wide the highlight
// should be compared to the entire width of the gradient and
// is used to calculate the positions of the 3 gradient colors.
// If the highlight is 20% width of the gradient, then the
// 'start locations' would be [-0.2, -0.1, 0.0] and the
// 'end locations' would be [1.0, 1.1, 1.2]

// If the gradient highlight ratio is wide, then it can
// 'bleed' over into the visible space of the view, which
// looks particularly bad if there is a pause between the
// animation repeating.
// Shifting the start and end points of the gradient by the
// size of the highlight prevents this.

let animationKeyPath = "locations"

let shimmerAnimation = CABasicAnimation(keyPath: animationKeyPath)
shimmerAnimation.fromValue = startLocations
shimmerAnimation.toValue = endLocations
shimmerAnimation.duration = animationDuration
shimmerAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)

let animationGroup = CAAnimationGroup()
animationGroup.duration = animationDuration + animationDelay
animationGroup.repeatCount = .infinity
animationGroup.animations = [shimmerAnimation]

// removes animation with same key (if exists) then adds
// the new animation
}
}


In the UIButton subclass I've added property observers to each of the properties that calls addShimmerAnimation() with any property change.

I also considered just supplying default values and requiring addShimmerAnimation() to be called manually once properties were configured. Another route was not having any public properties exposed and instead passing everything in through an initializer, but that would remove the possibility of these classes being used in a storyboard (which is an option I like to leave open) and having properties exposed through tagging the properties with IBInspectable.

class ShimmerButton: UIButton, ShimmerEffect {

override static var layerClass: AnyClass {
}

}

var animationDuration: TimeInterval = 3 {
}
var animationDelay: TimeInterval = 1.5 {
}

var gradientHighlightRatio: Double = 0.3 {
}

var gradientTint: UIColor = .black {
}

var gradientHighlight: UIColor = .white {
}

override init(frame: CGRect) {
super.init(frame: frame)
}

}
}


Example usage:

let shimmer = ShimmerButton()
shimmer.setTitle("Find new skills", for: .normal)
shimmer.titleLabel?.font = UIFont.systemFont(ofSize: 24, weight: UIFontWeightHeavy)

What frustrates me is that UIView, UILabel and UIButton only have minor differences. I wish there was a way for the computed properties to be extracted into a common place.
Example of ShimmerButton and ShimmerView (a UIView subclass) being used together: