在Swift中为UITextField / UIView摇动动画

时间:2015-01-16 15:15:26

标签: ios swift uitextfield

我试图找出当用户将文本字段留空时如何在按下按钮时使文本字段抖动。

我目前使用以下代码:

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 {

}

但我认为将文本字段震动作为警示会更具吸引力。

我找不到任何动画文字字段的内容。

有什么想法吗?

谢谢!

10 个答案:

答案 0 :(得分:128)

您可以更改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")

答案 1 :(得分:120)

在任何视图中都使用以下功能。

extension UIView {
    func shake() {
        let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
        animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
        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")
    }
}

答案 2 :(得分:37)

如果你想要更多参数(swift 3中的和swift 4 ),你可以使用它:

public extension UIView {

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

        let animation : CABasicAnimation = CABasicAnimation(keyPath: "transform.translation.x")
        animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
        animation.repeatCount = count
        animation.duration = duration/TimeInterval(animation.repeatCount)
        animation.autoreverses = true
        animation.fromValue = NSValue(cgPoint: CGPoint(x: -translation, y: self.center.y))
        animation.toValue = NSValue(cgPoint: CGPoint(x: translation, y: self.center.y))
        layer.add(animation, forKey: "shake")
    }  
}

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

yourView.shake()

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

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

答案 3 :(得分:20)

我认为所有这些都很危险。

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

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

答案 4 :(得分:9)

Swift 3.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()

答案 5 :(得分:3)

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

答案 6 :(得分:1)

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])

}

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

答案 7 :(得分:1)

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

答案 8 :(得分:0)

这是基于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..")
        }
    }
}

答案 9 :(得分:0)

我尝试了一些可用的解决方案,但没有一个正在处理完全抖动动画:从左向右移动并回到原始位置。

因此,经过一番调查,我发现使用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()
}

最终结果:

shake-animation-result