【问题标题】:Animation End Callback for CALayer?CALayer的动画结束回调?
【发布时间】:2010-09-22 18:09:00
【问题描述】:

我想知道 CALayer 中动画的回调在哪里(或者是否有任何东西)。具体来说,对于隐含的动画,比如改变框架、位置等。在 UIView 中,您可以执行以下操作:

[UIView beginAnimations:@"SlideOut" context:nil];
[UIView setAnimationDuration:.3];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animateOut:finished:context:)];
CGRect frame = self.frame;
frame.origin.y = 480;
self.frame = frame;
[UIView commitAnimations];

具体来说,setAnimationDidStopSelector 是我想要的 CALayer 中的动画。有这样的吗?

TIA。

【问题讨论】:

  • 对于任何在这里谷歌搜索的人,我已经为这个令人难以置信的古老问题提供了一个现代答案! :O 搜索到“2017...”

标签: iphone core-animation


【解决方案1】:

您可以使用 CATransaction,它有一个完成块处理程序。

[CATransaction begin];
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
[pathAnimation setDuration:1];
[pathAnimation setFromValue:[NSNumber numberWithFloat:0.0f]];    
[pathAnimation setToValue:[NSNumber numberWithFloat:1.0f]];
[CATransaction setCompletionBlock:^{_lastPoint = _currentPoint; _currentPoint = CGPointMake(_lastPoint.x + _wormStepHorizontalValue, _wormStepVerticalValue);}];
[_pathLayer addAnimation:pathAnimation forKey:@"strokeEnd"];
[CATransaction commit];

【讨论】:

  • 请注意,在将动画添加到图层之前设置完成块很重要。
  • 这并不总是有用,因为即使没有完成,当您删除动画时也会调用您。
【解决方案2】:

我回答了我自己的问题。您必须像这样使用CABasicAnimation 添加动画:

CABasicAnimation* anim = [CABasicAnimation animationWithKeyPath:@"frame"];
anim.fromValue = [NSValue valueWithCGRect:layer.frame];
anim.toValue = [NSValue valueWithCGRect:frame];
anim.delegate = self;
[layer addAnimation:anim forKey:@"frame"];

并实现委托方法animationDidStop:finished:,你应该很高兴。谢天谢地,这个功能存在! :D

【讨论】:

  • 这个答案对于关于委托的信息很有用,但它有一个很大的缺陷——你不能为“框架”设置动画,因为它是一个派生属性。 developer.apple.com/library/mac/#qa/qa2008/qa1620.html
  • 你不能编辑'frame',但是获取框架的中心和动画位置同样容易,例如 --> let theAnimation = CABasicAnimation(keyPath: "position");然后获取帧中心点 --> theAnimation.fromValue = NSValue(cgPoint: CGPoint(x: rightImage.frame.origin.x + rightImage.frame.width / 2.0, y: rightImage.frame.origin.y + rightImage .frame.height / 2.0))
  • 请注意,这个 10 年前的答案真的不是要走的路。 (关于 SO 的许多旧答案都是如此!)
  • @Fattie - 为什么会这样?有没有我错过的弃用通知?
【解决方案3】:

2018 年 ...

再简单不过了。

不要忘记[weak self],否则你会崩溃。

func animeExample() {
    
    CATransaction.begin()
    
    let a = CABasicAnimation(keyPath: "fillColor")
    a.fromValue, duration = ... etc etc
    
    CATransaction.setCompletionBlock{ [weak self] in
        self?.animeExample()
        self?.ringBell()
        print("again...")
    }
    
    someLayer.add(a, forKey: nil)
    CATransaction.commit()
}

关键提示:

您必须拥有setCompletionBlock之前someLayer.add。

顺序很关键!这是 iOS 的怪癖。

在示例中,它只是再次调用自身。

当然,你可以调用任何函数。


iOS 动画新手注意事项:

  1. “键”(如forKey)不相关且很少使用。将其设置为零。如果你想设置它,设置它为“任意字符串”。

  2. “keyPath”实际上是实际的“您正在制作动画的东西”。它实际上是图层的属性,例如“不透明度”、“背景颜色”等,但写成字符串。 (您不能只在此处输入“任何您想要的”,它必须是图层实际属性的名称,并且必须是可动画的。)

重复一遍:“key”(很少使用 - 只需将其设置为 nil)和“keyPath”彼此完全无关。

您经常会看到这两者混淆的示例代码(感谢愚蠢的命名),这会导致各种问题。


请注意,您可以交替使用委托,但仅使用完成块要容易得多,因为 (A) 它是独立的,可以在任何地方使用,并且 (B) 您通常有多个动画,其中使用委托的情况很无聊。

【讨论】:

  • 很好的答案 Fattie - 谢谢!您介意详细解释[weak self] 部分吗?对我来说,没有它也可以。
  • 嗨@ixany - 如果你不使用弱自我,它会在动画期间视图消失时崩溃。这是 iOS 工程的基础知识,您可以在此处阅读许多关于它的 QA!享受吧。
【解决方案4】:

这是基于 bennythemink 解决方案的 Swift 3.0 中的答案:

    // Begin the transaction
    CATransaction.begin()
    let animation = CABasicAnimation(keyPath: "strokeEnd")
    animation.duration = duration //duration is the number of seconds
    animation.fromValue = 0
    animation.toValue = 1
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
    circleLayer.strokeEnd = 1.0

    // Callback function
    CATransaction.setCompletionBlock { 
        print("end animation")
    }

    // Do the actual animation and commit the transaction
    circleLayer.add(animation, forKey: "animateCircle")
    CATransaction.commit() 

【讨论】:

    【解决方案5】:

    在这个垃圾上浪费了 4 个小时,只是为了淡入淡出。 注意代码中的注释。

       [CATransaction begin];
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
        animation.duration = 0.3;
        animation.fromValue = [NSNumber numberWithFloat:0.0f];
        animation.toValue = [NSNumber numberWithFloat:1.0f];
        animation.removedOnCompletion = NO;
        animation.fillMode = kCAFillModeBoth;
      ///  [box addAnimation:animation forKey:@"j"]; Animation will not work if added here. Need to add this only after the completion block.
    
        [CATransaction setCompletionBlock:^{
    
            CABasicAnimation *animation2 = [CABasicAnimation animationWithKeyPath:@"opacity"];
            animation2.duration = 0.3;
            animation2.beginTime = CACurrentMediaTime()+1;
            animation2.fromValue = [NSNumber numberWithFloat:1.0f];
            animation2.toValue = [NSNumber numberWithFloat:0.0f];
            animation2.removedOnCompletion = NO;
            animation2.fillMode = kCAFillModeBoth;
            [box addAnimation:animation2 forKey:@"k"];
    
        }];
    
        [box addAnimation:animation forKey:@"j"];
    
        [CATransaction commit];
    

    【讨论】:

    • 我猜,在你的原因中你可以使用 autoreverse 属性,因为你所做的基本上是反转第一个动画。
    • 这个回答笑死我了!我一直在那里试图让一件看似很小的事情工作几个小时......✊
    • 他们说您不应该使用animation.removedOnCompletion = NO;,而是在启动动画之前设置图层的值。这样你就搞砸了表示层和模型层..
    【解决方案6】:

    对于在 Google 上找到此页面的用户请注意:您确实可以通过将动画对象的“delegate”属性设置为将接收通知的对象并在其中实现“animationDidStop”方法来完成工作对象的 .m 文件。我刚刚尝试过,它有效。我不知道为什么 Joe Blow 说这不是正确的方法。

    【讨论】:

    • 使用 setCompletionBlock 和 CATransation.begin 尝试了从 removeAllAnimations 到特定 CAAnimations 的所有内容,并像 user3077725 的回答一样提交。试过 UIView.animateWIthDuration。不适用于简单的 alpha 和 position.x 动画。委托方法是唯一正常工作的方法
    【解决方案7】:

    在 Swift 4+ 我刚刚添加了delegate

    class CircleView: UIView,CAAnimationDelegate {
    ...
    
    let animation = CABasicAnimation(keyPath: "strokeEnd")
    animation.delegate = self//Set delegate
    

    动画完成回调 -

    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
         print("Animation END")
      }
    

    【讨论】:

      【解决方案8】:

      Swift 5.0

      func blinkShadow(completion: @escaping (() -> Void)) {
          CATransaction.begin()
          let animation = CABasicAnimation(keyPath: "shadowRadius")
          animation.fromValue = layer.shadowRadius
          animation.toValue = 0.0
          animation.duration = 0.1
          animation.autoreverses = true
          CATransaction.setCompletionBlock(completion)
          layer.add(animation, forKey: nil)
          CATransaction.commit()
      }
      

      【讨论】:

      • 这对我很有用,但我必须使用:Swift 5 中的 CATransaction.setCompletionBlock(completion) 并确保:animation.fillMode = .forwards animation.isRemovedOnCompletion = false 设置为确保链接在一起的任何动画都不会因链接项目而中断。谢谢!
      【解决方案9】:

      您可以在设置 CAAnimation 对象时设置给定动画的名称。在animationDiStop:finished中,只需比较提供的Animation对象的名称,即可根据动画执行特定的功能。

      【讨论】:

      • 没有name属性?
      【解决方案10】:

      2020 年 ...

      ValueAnimator,更新你的自定义属性。

      https://github.com/Only-IceSoul/ios-jjvalueanimator

       class OnAnimationListener : AnimatorListener {
      
              weak var s : ViewController?
      
              init(_ ins: ViewController) {
                  s = ins
              }
              func onAnimationStart(_ animation: Animator) {}
              func onAnimationEnd(_ animation: Animator) {
      
                 print("end")
                 s?.label.text = "end"
      
              }
              func onAnimationCancel(_ animation: Animator) {}
              func onAnimationRepeat(_ animation: Animator) {}
      
          }
      

      【讨论】:

        【解决方案11】:

        我在 CAAnimation 上编写了一个扩展,它为您提供了一个开始和一个完成的关闭,因为我已经厌倦了实现委托,特别是对于多个动画,您必须做一些可怕的事情,比如使用动画的键来查看哪个动画正在调用委托 - 让这类事情变得非常简单。

        在 GitHub 上 - Animation Actions

        希望对某人有用!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-06-07
          • 2016-11-19
          • 2023-04-06
          • 2015-09-29
          • 2013-12-15
          相关资源
          最近更新 更多