-->

CABasicAnimation不工作时的方法是从viewDidLoad中称为(CABasicAni

2019-10-17 07:47发布

我有添加到已呈现为modalViewController,风格水平翻转视图中的一个ImageView的。 我加入以下代码制作动画的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的。

但是,当我尝试下面的代码它的工作原理:

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

我的问题是,为什么这个问题是怎么回事? 是否有任何区别,

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

[self animateTheImageview:self.lightImage];

Answer 1:

你不应该在viewDidLoad中执行任何动画,并且还调用[超级viewDidLoad中在它,因为你只是覆盖它。 尝试在viewWillAppear中或viewDidAppear显示它。

然后,根据NSObject的参考 ,performSelectorOnMainThread:withObject:waitUntilDone:

队列主线程的运行循环的消息

因此,在队列中的其他消息可能在执行完成动画之前先。

希望这可以帮助



文章来源: CABasicAnimation is not working when the method is called from the viewDidLoad