Swift 中 UITextField/UIView 的摇动动画

Shake Animation for UITextField/UIView in Swift

我正在尝试弄清楚当用户将文本字段留空时如何使文本字段在按下按钮时抖动。

我目前可以使用以下代码:

if self.subTotalAmountData.text == "" {

    let alertController = UIAlertController(title: "Title", message:
        "What is the Sub-Total!", preferredStyle: UIAlertControllerStyle.Alert)
    alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default,handler: nil))

    self.presentViewController(alertController, animated: true, completion: nil)

} else {

}

但我认为将文本字段摇动作为提醒会更有吸引力。

我找不到任何动画文本字段。

有什么想法吗?

谢谢!

您可以更改 durationrepeatCount 并进行调整。这就是我在我的代码中使用的。改变 fromValuetoValue 将改变摇动中移动的距离。

let animation = CABasicAnimation(keyPath: "position")
animation.duration = 0.07
animation.repeatCount = 4
animation.autoreverses = true
animation.fromValue = NSValue(cgPoint: CGPoint(x: viewToShake.center.x - 10, y: viewToShake.center.y))
animation.toValue = NSValue(cgPoint: CGPoint(x: viewToShake.center.x + 10, y: viewToShake.center.y))

viewToShake.layer.add(animation, forKey: "position")

以下函数在任意视图中使用

extension UIView {
    func shake() {
        let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
        animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
        animation.duration = 0.6
        animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0 ]
        layer.add(animation, forKey: "shake")
    }
}
extension CALayer {

    func shake(duration: NSTimeInterval = NSTimeInterval(0.5)) {

        let animationKey = "shake"
        removeAnimationForKey(animationKey)

        let kAnimation = CAKeyframeAnimation(keyPath: "transform.translation.x")
        kAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
        kAnimation.duration = duration

        var needOffset = CGRectGetWidth(frame) * 0.15,
        values = [CGFloat]()

        let minOffset = needOffset * 0.1

        repeat {

            values.append(-needOffset)
            values.append(needOffset)
            needOffset *= 0.5
        } while needOffset > minOffset

        values.append(0)
        kAnimation.values = values
        addAnimation(kAnimation, forKey: animationKey)
    }
}

使用方法:

[UIView, UILabel, UITextField, UIButton & etc].layer.shake(NSTimeInterval(0.7))

这是基于 CABasicAnimation 的,它还包含一个音频效果:

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..")
        }
    }
}

编辑:如果您连续两次触发动画,使用 CABasicAnimation 会导致应用程序崩溃。所以一定要使用CAKeyframeAnimation。错误已修复,感谢评论:)


或者如果你想要更多的参数,你可以使用这个(in swift 5):

public extension UIView {

    func shake(count : Float = 4,for duration : TimeInterval = 0.5,withTranslation translation : Float = 5) {

        let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
        animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
        animation.repeatCount = count
        animation.duration = duration/TimeInterval(animation.repeatCount)
        animation.autoreverses = true
        animation.values = [translation, -translation]
        layer.add(animation, forKey: "shake")
    }  
}

您可以在任何 UIView、UIButton、UILabel、UITextView 等上调用此函数。这样

yourView.shake()

或者如果你想给动画添加一些自定义参数,也可以这样:

yourView.shake(count: 5, for: 1.5, withTranslation: 10)

Swift 5.0

extension UIView {
    func shake(){
        let animation = CABasicAnimation(keyPath: "position")
        animation.duration = 0.07
        animation.repeatCount = 3
        animation.autoreverses = true
        animation.fromValue = NSValue(cgPoint: CGPoint(x: self.center.x - 10, y: self.center.y))
        animation.toValue = NSValue(cgPoint: CGPoint(x: self.center.x + 10, y: self.center.y))
        self.layer.add(animation, forKey: "position")
    }
}

要使用

self.vwOffer.shake()

我认为所有这些都是危险的。

如果您的摇动动画基于用户操作,并且在设置动画时触发了该用户操作。

CRAAAAAASH

这是我的方法 Swift 4:

static func shake(view: UIView, for duration: TimeInterval = 0.5, withTranslation translation: CGFloat = 10) {
    let propertyAnimator = UIViewPropertyAnimator(duration: duration, dampingRatio: 0.3) {
        view.transform = CGAffineTransform(translationX: translation, y: 0)
    }

    propertyAnimator.addAnimations({
        view.transform = CGAffineTransform(translationX: 0, y: 0)
    }, delayFactor: 0.2)

    propertyAnimator.startAnimation()
}

可能不是最干净的,但是这个方法可以反复触发,容易理解

编辑:

我非常支持使用 UIViewPropertyAnimator。如此多的炫酷功能,让您可以对基本动画进行动态修改。

这是另一个在视图摇动时添加红色边框,然后在摇动结束时将其移除的示例。

static func shake(view: UIView, for duration: TimeInterval = 0.5, withTranslation translation: CGFloat = 10) {
    let propertyAnimator = UIViewPropertyAnimator(duration: duration, dampingRatio: 0.3) {
        view.layer.borderColor = UIColor.red.cgColor
        view.layer.borderWidth = 1
        view.transform = CGAffineTransform(translationX: translation, y: 0)
    }

    propertyAnimator.addAnimations({
        view.transform = CGAffineTransform(translationX: 0, y: 0)
    }, delayFactor: 0.2)

    propertyAnimator.addCompletion { (_) in
        view.layer.borderWidth = 0
    }

    propertyAnimator.startAnimation()
}
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])

}

//写在基础class或任何视图控制器中并使用它

Swift 5

Corey Pett 答案的安全(非崩溃)摇动扩展:

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()
    }
}

我尝试了一些可用的解决方案,但其中 none 正在处理 full shake 动画:从左向右移动并返回到原始位置。

因此,经过一些调查后,我找到了正确的解决方案,我认为使用 UIViewPropertyAnimator 可以成功摇动。

func shake(completion: (() -> Void)? = nil) {
    let speed = 0.75
    let time = 1.0 * speed - 0.15
    let timeFactor = CGFloat(time / 4)
    let animationDelays = [timeFactor, timeFactor * 2, timeFactor * 3]

    let shakeAnimator = UIViewPropertyAnimator(duration: time, dampingRatio: 0.3)
    // left, right, left, center
    shakeAnimator.addAnimations({
        self.transform = CGAffineTransform(translationX: 20, y: 0)
    })
    shakeAnimator.addAnimations({
        self.transform = CGAffineTransform(translationX: -20, y: 0)
    }, delayFactor: animationDelays[0])
    shakeAnimator.addAnimations({
        self.transform = CGAffineTransform(translationX: 20, y: 0)
    }, delayFactor: animationDelays[1])
    shakeAnimator.addAnimations({
        self.transform = CGAffineTransform(translationX: 0, y: 0)
    }, delayFactor: animationDelays[2])
    shakeAnimator.startAnimation()

    shakeAnimator.addCompletion { _ in
        completion?()
    }

    shakeAnimator.startAnimation()
}

最终结果: