CAShapeLayer 动画不触发动画确实停止



使用 Swift 3.0 运行 tvOS

基本应用程序,这是视图控制器中的代码...我想在淡出CAShapeLayer后将其删除。动画工作得很好,但完成方法animationDidStop永远不会被调用?

想要使用override func animationDidStop方法,但它不会编译。给了我错误"方法不会覆盖其超类中的任何方法",这肯定是错误的,animationDidStopCAAnimation类的成员。

这段代码有什么问题?我可以用计时器或我猜的东西来解决这个问题,但这是一种软糖。

import UIKit
import QuartzCore

class ViewController: UIViewController, CALayerDelegate, CAAnimationDelegate {
var shapeLayer = CAShapeLayer()

override func viewDidLoad() {
    super.viewDidLoad()
    highlight(XCord: 100, YCord: 100)
    clearhighlight()
    // Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
func highlight(XCord: CGFloat, YCord: CGFloat) {
    DispatchQueue.main.async {
        let circlePath = UIBezierPath(arcCenter: CGPoint(x: XCord,y: YCord), radius: CGFloat(20), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
        self.shapeLayer.path = circlePath.cgPath
        //change the fill color
        //shapeLayer.fillColor = UIColor.clear.cgColor
        self.shapeLayer.fillColor = UIColor.red.cgColor
        self.shapeLayer.opacity = 0.5
        self.shapeLayer.fillRule = kCAFillRuleEvenOdd
        //you can change the stroke color
        self.shapeLayer.strokeColor =  UIColor.red.cgColor
        //you can change the line width
        self.shapeLayer.lineWidth = 3.0
        DispatchQueue.main.async {
            self.view.layer.addSublayer(self.shapeLayer)
        }
    }
}
func clearhighlight() {
    DispatchQueue.main.async {
        let fadeInAndOut = CABasicAnimation(keyPath: "opacity")
        fadeInAndOut.duration = 10.0;
        //fadeInAndOut.autoreverses = true;
        fadeInAndOut.repeatCount = 1
        fadeInAndOut.fromValue = 1.0
        fadeInAndOut.toValue = 0.0
        fadeInAndOut.isRemovedOnCompletion = true
        fadeInAndOut.fillMode = kCAFillModeForwards;
        //self.view.layer.delegate = self
        self.shapeLayer.delegate = self
        self.shapeLayer.add(fadeInAndOut, forKey: "fadeOut")
        self.shapeLayer.setNeedsDisplay()
    }
}
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
    print("animationDidStop")
    DispatchQueue.main.async {
        self.shapeLayer.removeFromSuperlayer()
    }
}

}

您正在设置形状图层的委托:

self.shapeLayer.delegate = self

但是,如果要调用animationDidStop,则必须设置动画的delegate,而不是图层的:

fadeInAndOut.delegate = self

你说:

想要使用override func animationDidStop方法,但它不会编译。给了我错误"方法不会覆盖其超类中的任何方法",这肯定是错误的,animationDidStopCAAnimation类的成员。

您正在视图控制器中实现这一点,并且UIViewController不提供animationDidStop的基类实现,因此没有什么可以覆盖的。

animationDidStop是由CAAnimationDelegate协议定义的方法,因此 (a( 视图控制器应声明其符合该协议;(b( 不要使用 override 关键字。

最新更新