从viewDidLoad调用方法时,CABasicAnimation不起作用
我有一个imageView添加到一个显示为modalViewController的视图中,具有水平翻转样式. 我添加了以下代码来为imageView设置动画.
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];
}
}
我正在从viewDidLoad
调用此方法:
- (void)viewDidLoad
{
[self switchOnorOff];
}
我的问题是上面的代码没有为imageView设置动画.
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];
和
[self animateTheImageview:self.lightImage];
您不应在viewDidLoad中执行任何动画,并应在其中调用[super viewDidLoad],因为您只是对其进行了覆盖. 尝试在viewWillAppear或viewDidAppear上显示它.
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.
希望这会有所帮助