9

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

PugLvr28
  • 111
  • 1
  • 1
  • 6

5 Answers5

15

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
}
linimin
  • 6,239
  • 2
  • 26
  • 31
  • 1
    @PugLvr28 Looks like you're new here. You should accept Swipesight's answer if it solved your problem. – Matt Long Nov 19 '14 at 06:51
10

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(CALayer.opacity))
animation.fromValue = 0.0
animation.toValue = 1.0
animation.duration = 1.0
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
element.layer?.addAnimation(animation, forKey: "fade")
laka
  • 644
  • 8
  • 23
R.Wonder
  • 151
  • 2
  • 8
2

You can use this extension method (unless you want to modify the view's attributes itself):

extension CALayer {

    func flash(duration: TimeInterval) -> Observable<Void> {
        let flash = CABasicAnimation(keyPath: "opacity")

        flash.fromValue = NSNumber(value: 0)
        flash.toValue = NSNumber(value: 1)
        flash.duration = duration
        flash.autoreverses = true

        removeAnimation(forKey: "flashAnimation")
        add(flash, forKey: "flashAnimation")
        opacity = 0     // Change the actual data value in the layer to the final value
    }
}
SoftDesigner
  • 5,640
  • 3
  • 58
  • 47
1

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)
user4746643
  • 11
  • 1
  • 1
-1

Thanks to @ylin0x81. For swift 5 i had to do:

cell.imageView.alpha = 0.0;
UIView.animate(withDuration: 1.0) {
    cell.imageView.alpha = 1
}
metamagikum
  • 1,307
  • 15
  • 19