-->

How do I animate opacity using swift?

2019-02-22 18:46发布

问题:

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!~

回答1:

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
}


回答2:

You can also write it like this:

animation.fromValue = 0.0
animation.toValue = 1.0

The whole 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:

If anyone is looking to use CABasicAnimation like OP had originally tried to do, one problem with his original code was he was using NSValue for the toValue. I switched it to NSNumber and it worked for me. Like this

    fadeToVisible.fromValue = NSNumber(float: 0.0)