How do I animate opacity using swift?

PugLvr28 picture PugLvr28 · Nov 18, 2014 · Viewed 11.1k times · Source

Could someone please provide me with an example of animating the opacity of an Image View in swift??

I couldn't even find a good example in objective 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 completely sure though), could someone please help me?

element = an Image View

Thanks in advance!~

Answer

ylin0x81 picture ylin0x81 · Nov 18, 2014

If you need a simple animation, why not just use UIView's animateWithDuration:animations: method?

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