Shake Animation for UITextField/UIView in Swift

后端 未结 10 1408
梦毁少年i
梦毁少年i 2020-12-07 09:37

I am trying to figure out how to make the text Field shake on button press when the user leaves the text field blank.

I currently have the following code working:

10条回答
  •  悲&欢浪女
    2020-12-07 10:22

    Swift 5

    Safe (non crash) shake extension for Corey Pett answer:

    extension UIView {
        func shake(for duration: TimeInterval = 0.5, withTranslation translation: CGFloat = 10) {
            let propertyAnimator = UIViewPropertyAnimator(duration: duration, dampingRatio: 0.3) {
                self.transform = CGAffineTransform(translationX: translation, y: 0)
            }
    
            propertyAnimator.addAnimations({
                self.transform = CGAffineTransform(translationX: 0, y: 0)
            }, delayFactor: 0.2)
    
            propertyAnimator.startAnimation()
        }
    }
    

提交回复
热议问题