更改UILabel的文本会在使用UIViewKeyframeAnimations时重新出现

时间:2014-10-16 10:27:35

标签: ios uiview uiviewanimation

我想在UILabel上执行一系列动画,因此我查找了iOS7中添加的UIViewKeyframeAnimations

我想要做的简化版本是:

  1. 淡出UILabel,持续时间为0.5秒
  2. 等一下
  3. 使用持续时间为0.5秒的新文本淡入UILabel

    NSTimeInterval duration = 2;
    [UIView animateKeyframesWithDuration:duration delay:0 options:UIViewKeyframeAnimationOptionAllowUserInteraction | UIViewAnimationOptionOverrideInheritedOptions animations:^{
        [UIView addKeyframeWithRelativeStartTime:0 relativeDuration:0.5/duration animations:^{
            self.label.alpha = 0;
        }];
    
        [UIView addKeyframeWithRelativeStartTime:1.5/duration relativeDuration:0.5/duration animations:^{
            self.label.text = [@(arc4random_uniform(4000)) stringValue];
            self.label.alpha = 1;
        }];
    } completion:nil];
    
  4. 结果是标签文本淡出并重新显示新文本,然后再次淡出并再次淡入。

    结果视频:Animation Failure

    干杯 的Morten

2 个答案:

答案 0 :(得分:1)

您声明:“结果是标签文字淡出并重新显示新文本,然后再次淡出并再次淡入。”。然而,我在电影中看到的是,alpha转换只是按预期工作,淡出和淡入。你想要的行为的唯一例外是文本更改已经在动画开始时应用,而不是在动画的第二个关键帧的开头。

了解一旦调用animateKeyframesWithDuration,addKeyframeWithRelativeStartTime块中的代码就会被执行,这一点很重要。任何可动画的变化(帧,alpha等)都将被动画化。同样,任何不是自动动画视图属性的内容(例如标签的文本更改)都会立即显示。

为了帮助说明这一点,请尝试在所有动画块(animateKeyframesWithDuration和addKeyframeWithRelativeStartTime)的开头放置一个NSLog语句,并在完成块中放置一个。您将看到完成块中的每个NSLog 除外)具有完全相同的日志时间。

由于这个原因,下面的代码将工作,因为整个块的执行被推迟到第一个动画结束:

[UIView animateWithDuration:1 animations:^{
    self.label.alpha = 0;
} completion:^(BOOL finished) {
    self.label.text = [@(arc4random_uniform(4000)) stringValue];
    [UIView animateWithDuration:1 animations:^{
        self.label.alpha = 1;
    }];
}];

答案 1 :(得分:0)

以下是我要做的事情:不使用关键帧来制作像这样的简单动画,我会使用带动画的动画:

[UIView animateWithDuration:0.25 animations:^
 {
     [self.label setAlpha:0.0];
     [self.imageview setAlpha:0.0];
 }
                 completion: ^(BOOL completed)
 {

     [UIView animateWithDuration:0.25 delay:0.5 options:UIViewAnimationOptionAllowUserInteraction animations:^
      {
          self.label.text = [@(arc4random_uniform(4000)) stringValue];
          [self.label setAlpha:1.0];
      }
                      completion: ^(BOOL completed)
      {

      }
      ];
     [UIView animateWithDuration:1.0 delay:0.5 options:UIViewAnimationOptionAllowUserInteraction animations:^
      {
          [self.imageview setAlpha:1.0];
          [self.imageview setFrame:frame];
      }
                      completion: ^(BOOL completed)
      {
          //if you need to do stuff after the animations finish, here you can do them.
      }
      ];
 }
 ];
相关问题