35

Before this code, my movie pic alpha is set to 0,

CABasicAnimation* fadein= [CABasicAnimation animationWithKeyPath:@"alpha"];
    [fadein setToValue:[NSNumber numberWithFloat:1.0]];
    [fadein setDuration:0.5];
    [[moviepic layer]addAnimation:fadein forKey:@"alpha"];

Nothing happened, if I set alpha to 0.5 beforehand instead, the alpha remains at 0.5 and not animating to 1.

I've seen a code using UIView beginAnimations: around, but I'm teaching core animation so I wondered why CABasicAnimation can't do simple task like this?

5argon
  • 3,683
  • 3
  • 31
  • 57

3 Answers3

105
[CABasicAnimation animationWithKeyPath:@"opacity"];

UIView exposes this as alpha where as CALayer exposes this as opacity.

Evan
  • 6,151
  • 1
  • 26
  • 43
ohho
  • 50,879
  • 75
  • 256
  • 383
  • What O_o I'll try this soon. But is there anymore case like this? And where can I check that what can I use for KeyPath? (normally I'd check on object's property which has setAlpha in it but in this case it doesn't match...) – 5argon Sep 23 '11 at 16:30
  • 4
    @Sargon With Core Animation you are animating `CALayer` properties, not `UIView` properties, so the layer is the place to look for correct property names - see: `view.layer`. – Palimondo Sep 27 '11 at 12:23
2

For Swift:

let opacity = CABasicAnimation(keyPath: "opacity")
opacity.fromValue = fromValue
opacity.toValue = toValue
opacity.duration = duration
opacity.beginTime = CACurrentMediaTime() + beginTime  //If a delay is needed

view.layer.add(opacity, forKey: nil)

If you want to keep the final alpha value, you have to set the current view controller as the delegate of the opacity animation:

opacity.delegate = self

And, in the delegate function animationDidStop, you should do:

extension ViewController: CAAnimationDelegate {

    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {   
        view.alpha = toValue
    }
}
Ginés SM
  • 233
  • 2
  • 5
1

@ohho answers the posted question. Mine will be a bit more generic. For a list what can and how be animated with CABasicAnimation please refer to Apple's documentation

Julian
  • 9,299
  • 5
  • 48
  • 65