Shake Animation for UITextField/UIView in Swift

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

    func shakeTextField(textField: UITextField)
    {
        let animation = CABasicAnimation(keyPath: "position")
        animation.duration = 0.07
        animation.repeatCount = 3
        animation.autoreverses = true
        animation.fromValue = NSValue(cgPoint: CGPoint(x: textField.center.x - 10, y: textField.center.y))
        animation.toValue = NSValue(cgPoint: CGPoint(x: textField.center.x + 10, y: textField.center.y))
        textField.layer.add(animation, forKey: "position")
    
        textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder ?? "",
                                                             attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])
    
    }
    

    //write in base class or any view controller and use it

提交回复
热议问题