Shake Animation for UITextField/UIView in Swift

后端 未结 10 1419
梦毁少年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:19

    This is based on CABasicAnimation, it contain also an audio effect :

    extension UIView{
        var audioPlayer = AVAudioPlayer()
        func vibrate(){
            let animation = CABasicAnimation(keyPath: "position")
            animation.duration = 0.05
            animation.repeatCount = 5
            animation.autoreverses = true
            animation.fromValue = NSValue(CGPoint: CGPointMake(self.center.x - 5.0, self.center.y))
            animation.toValue = NSValue(CGPoint: CGPointMake(self.center.x + 5.0, self.center.y))
            self.layer.addAnimation(animation, forKey: "position")
            // audio part
            do {
                audioPlayer =  try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(mySoundFileName, ofType: "mp3")!))
                audioPlayer.prepareToPlay()
                audioPlayer.play()
    
            } catch {
                print("∙ Error playing vibrate sound..")
            }
        }
    }
    

提交回复
热议问题