CABasicAnimation is not working when the method is called from the viewDidLoad
Asked Answered
S

1

0

I have an imageView added to a view that's presented as a modalViewController, with style horizontal flip. I have added the following code for animating the imageView.

- (void)animateTheImageview:(UIImageView*) imageViewToAnimate{
    
    CABasicAnimation *fadeAnimation;
    fadeAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeAnimation.duration = 1.5;
    fadeAnimation.repeatCount = INFINITY;
    fadeAnimation.autoreverses = NO;
    fadeAnimation.fromValue = [NSNumber numberWithFloat:1.0];
    fadeAnimation.toValue = [NSNumber numberWithFloat:0.5];
    fadeAnimation.removedOnCompletion = YES;
    fadeAnimation.fillMode = kCAFillModeForwards;
    [imageViewToAnimate.layer addAnimation:fadeAnimation forKey:@"animateOpacity"]; 
}


- (void)switchOnorOff
 {
    
    if (onOffSwitch.on)
    {
        
        self.lightImage.image = [UIImage imageNamed:@"CFLGlow.jpg"];
        [self animateTheImageview:self.lightImage];
    }
    else
    {
        
        self.lightImage.image = [UIImage imageNamed:@"CFL-BULB.jpg"];
        [self.lightImage.layer removeAllAnimations];
    }
}

And I'm calling this method from the viewDidLoad:

- (void)viewDidLoad
   {
      [self switchOnorOff];
   }

My issue is the above code doesn't animate the imageView.

But when I tried the below code it works:

[self performSelectorOnMainThread:@selector(animateTheImageview:) withObject:self.lightImage waitUntilDone:YES];

My question is why this issue is happening ? Is there any difference between,

[self performSelectorOnMainThread:@selector(animateTheImageview:) withObject:self.lightImage waitUntilDone:YES];

and

[self animateTheImageview:self.lightImage];

Susy answered 25/10, 2012 at 9:31 Comment(0)
A
7

You should not perform any animation in the viewDidLoad, and also call [super viewDidLoad] in it since you're just overriding it. Try displaying it on viewWillAppear or viewDidAppear.

Then, according to the NSObject Reference, performSelectorOnMainThread:withObject:waitUntilDone:

queues the message on the run loop of the main thread

So the other messages on queue may complete first before performing the animation.

Hope this helps

Aramenta answered 25/10, 2012 at 9:59 Comment(1)
Thank you, had same problem when placing animations in viewDidLoad inside pageViewController.Sikora

© 2022 - 2024 — McMap. All rights reserved.