【问题标题】:CABasicAnimation is not working when the method is called from the viewDidLoad从 viewDidLoad 调用该方法时,CABasicAnimation 不起作用
【发布时间】:2012-10-25 09:31:38
【问题描述】:

我有一个 imageView 添加到一个显示为 modalViewController 的视图中,带有样式水平翻转。 我添加了以下代码来为 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];

【问题讨论】:

    标签: ios cabasicanimation performselector


    【解决方案1】:

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

    然后,根据NSObject Reference,执行SelectorOnMainThread:withObject:waitUntilDone:

    在主线程的运行循环中对消息进行排队

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

    希望对你有帮助

    【讨论】:

    • 谢谢,在 pageViewController 中的 viewDidLoad 中放置动画时遇到了同样的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多