Skip to content

Instantly share code, notes, and snippets.

@enigmatic7earth
Last active May 23, 2018 12:30
Show Gist options
  • Save enigmatic7earth/6e0119d75ef847c77b360de4aa8937ee to your computer and use it in GitHub Desktop.
Save enigmatic7earth/6e0119d75ef847c77b360de4aa8937ee to your computer and use it in GitHub Desktop.
Display a red border around the textfield and shake it to indicate an error to user.
// Just call this funtion by passing to it the **required** view to which you wish to draw a user's attention.
func shake(viewToShake: UIView){
let colorAnimation = CABasicAnimation(keyPath: "borderColor")
colorAnimation.fromValue = UIColor.red.cgColor
colorAnimation.toValue = UIColor.lightGray.cgColor
viewToShake.layer.borderColor = UIColor.lightGray.cgColor
viewToShake.layer.borderWidth = 1
viewToShake.layer.cornerRadius = 5
let shakeAnimation = CABasicAnimation(keyPath: "position")
shakeAnimation.duration = 0.07
shakeAnimation.repeatCount = 4
shakeAnimation.autoreverses = false
shakeAnimation.fromValue = NSValue(cgPoint: CGPoint(x: viewToShake.center.x - 10, y: viewToShake.center.y))
shakeAnimation.toValue = NSValue(cgPoint: CGPoint(x: viewToShake.center.x + 10, y: viewToShake.center.y))
let errorAnimations = CAAnimationGroup()
errorAnimations.duration = 0.5
errorAnimations.animations = [colorAnimation,shakeAnimation]
errorAnimations.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
viewToShake.layer.add(errorAnimations, forKey: "color and shake")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment