How to update opacity using swift?

Can someone please provide me with an example of animating image opacity in swift ??

I couldn't even find a good example in object c

func showCorrectImage(element: AnyObject){

    var animation : CABasicAnimation = CABasicAnimation(keyPath: "opacity");

    animation.delegate = self

    animation.fromValue = NSValue(nonretainedObject: 0.0)
    animation.toValue = NSValue(nonretainedObject: 1.0)

    animation.duration = 1.0

    element.layer?.addAnimation(animation, forKey: nil)
}

      

I think I have most of this right (not really sure though), can someone help me?

element = image view

Thanks in advance! ~

+5


source to share


3 answers


If you want simple animation, why not just use the UIView method animateWithDuration:animations:

?



imageView.alpha = 0
UIView.animateWithDuration(1.0) {
        imageView.alpha = 1
}

      

+10


source


You can also write it like this:

animation.fromValue = 0.0
animation.toValue = 1.0

      



All the code should be like this:

let animation = CABasicAnimation(keyPath: "opacity")
animation.delegate = self
animation.fromValue = 0.0
animation.toValue = 1.0
animation.duration = 1.0
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
element.layer?.addAnimation(animation, forKey: "fade")

      

+3


source


If anyone wants to use CABasicAnimation as the OP originally tried to do, one problem with his source code was using NSValue for toValue. I switched it to NSNumber and it worked for me. Like this

    fadeToVisible.fromValue = NSNumber(float: 0.0)

      

+1


source







All Articles