【问题标题】:CATransaction completion being called immediately立即调用 CATransaction 完成
【发布时间】:2013-11-14 11:01:23
【问题描述】:

我试图在我的 CAAnimation 完成后执行一个完成块。但是,似乎在我的动画完成之前调用了动画块。动画仍然正确发生。

[CATransaction begin];
[self.view.layer addAnimation:self.dropAndBounceAnimation forKey:@"appearance"];
[CATransaction setCompletionBlock:completionBlock];
[CATransaction commit];

dropAndBounceAnimation 是 position.y 上的 CAKeyFrameAnimation,具有固定的持续时间。

【问题讨论】:

    标签: ios caanimation


    【解决方案1】:

    我不确定这是否真的是正确的解决方法,但是通过设置完成块在为图层添加动画,完成块始终在正确的时间被调用。

    [CATransaction begin];
    [CATransaction setCompletionBlock:completionBlock];
    [self.view.layer addAnimation:self.dropAndBounceAnimation forKey:@"appearance"];
    [CATransaction commit];
    

    【讨论】:

    • 是的,根据documentation:“保证在所有动画随后添加后立即(在主线程上)调用的完成块对象由该事务组完成(或已被删除。)”。关键部分是“后续添加”。
    • @albertamg 但是,它也声明了If no animations are added before the current transaction group is committed (or the completion block is set to a different value,) the block will be invoked immediately.
    • @iWasRobbed 是的,这解释了为什么如果在将动画添加到事务组之后设置块,则在动画完成之前调用块。
    • 如果您忘记设置view.wantsLayer = YES;,也会立即调用
    【解决方案2】:

    你需要在添加动画之前设置完成块。

    [CATransaction begin];
    [CATransaction setValue:[NSNumber numberWithFloat: 1.0f] forKey:kCATransactionAnimationDuration];
    
    [CATransaction setCompletionBlock:^{
    // ... whatever you want to do when the animation is complete
    }];
    
    [self.googleMapsView animateToCameraPosition:[GMSCameraPosition 
                        cameraWithLatitude:LATITUDE
                                 longitude:LONGITUDE
                                      zoom:ZOOM]];
    
    [CATransaction commit];
    

    这必须在视图上的动画完成后触发完成块。

    【讨论】:

      【解决方案3】:

      这里是 Swift 3.0.1, Xcode 8 版本:

      CATransaction.begin()
      
      CATransaction.setCompletionBlock({
        print("Transaction completed")
      })
      
      print("Transaction started")
      view.layer.add(dropAndBounceAnimation, forKey: "appearance")
      
      CATransaction.commit()
      

      【讨论】:

        【解决方案4】:

        尝试异步启动动画:

        DispatchQueue.main.async {
            self.startAnimation()
        }
        

        因为如果您在调用动画之前进行一些视图设置,它可能会干扰视图绘制。

        【讨论】:

          猜你喜欢
          • 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
          相关资源
          最近更新 更多