Shake Animation for UITextField/UIView in Swift

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

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

    How to use:

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

提交回复
热议问题