Exploring Shake Animation With Swift 3

Exploring Shake Animation With Swift 3

Welcoming all Xcoders!

Now a day its trend to highlight wrong input using SHAKE Animation so lest explore how you can shake any control in swift 3.

Keyframe animations offer extraordinary power for developers because they let you set multiple values and have iOS animate between them over times you specify.

Below we have written one simple function where you can pass the object of UIView that you want to shake and it will shake the view.

func shakeView(vw: UIView) {

let animation = CAKeyframeAnimation()

animation.keyPath = "position.x"

animation.values = [0, 10, -10, 10, -5, 5, -5, 0 ]

animation.keyTimes = [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1] animation.duration = 0.4

animation.isAdditive = true

vw.layer.add(animation, forKey: "shake")

}

Lets explore the code how actually it works.

Inherits From

CAPropertyAnimation

Here first we have created the object of CAKeyframeAnimation

You can create a CAKeyframeAnimation object using the inherited init(keyPath:) method, specifying the key path of the property that you want to animate on the layer. You can then specify the keyframe values to use to control the timing and animation behaviour.

animation.keyPath = "position.x"

Here we have defined the position of animation.

If we need shake animation Vertically we will define position.x and if we need Horizontal share animation then we will define position.y

Providing keyframe values

var values: [Any]?

An array of objects that specify the keyframe values to use for the animation.

var path: CGPath?

The path for a point-based property to follow.

Keyframe timing

var keyTimes: [NSNumber]?

An optional array of NSNumber objects that define the time at which to apply a given keyframe segment.

Animation Duration

Here we can define the time duration of animation in seconds.

animation.duration = 0.4

isAdditive

animation.values = [0, 10, -10, 10, -5, 5, -5, 0 ]

the animation is marked as additive, it means that 10 is relative to its starting position.

Download sample code from

https://github.com/ZetrixWeb-Swift-iOS/ZWAnimation-Shake

Reference

https://developer.apple.com/reference/quartzcore/cakeyframeanimation



要查看或添加评论,请登录

Himani Jivrani的更多文章

社区洞察

其他会员也浏览了