CAKeyframeAnimation 在笔尖中不起作用

CAKeyframeAnimation not working in nib

我有一个 nib 文件,它必须为视图设置动画以在圆形路径中移动。 但是当我 运行 我的代码时,我看到视图没有动画并且在我视图的顶角

这是我的代码

override func awakeFromNib() {

        let circlePath = UIBezierPath(arcCenter: CGPointMake(CGRectGetMidX(loadingview.bounds), CGRectGetMidY(loadingview.bounds)), radius: 30, startAngle: 0, endAngle:CGFloat(M_PI)*2, clockwise: true)

        let animation = CAKeyframeAnimation(keyPath: "position")
        animation.beginTime = 0.0
        animation.duration = 1
        animation.repeatCount = Float.infinity
        animation.path = circlePath.CGPath

        let squareView = UIView()
        squareView.frame = CGRectMake(0, 0, 10, 10);
        squareView.backgroundColor = UIColor.grayColor()

        self.addSubview(squareView)
        // You can also pass any unique string value for key


        // circleLayer is only used to locate the circle animation path
        let circleLayer = CAShapeLayer()
        circleLayer.path = circlePath.CGPath
        circleLayer.strokeColor = UIColor.blackColor().CGColor
        circleLayer.fillColor = UIColor.clearColor().CGColor
        loadingview.layer.addSublayer(circleLayer)

        squareView.layer.addAnimation(animation, forKey: "position")

        self.layer.shadowColor = UIColor.blackColor().CGColor
        self.layer.shadowOpacity = 1
        self.layer.shadowOffset = CGSize.zero
        self.layer.shadowRadius = 1
        self.layer.cornerRadius = 10.0
    }

您无法在 awakeFromNib 中开始动画。现在还为时过早。您只能对实际位于界面 view/layer 层次结构中的图层进行动画处理,而刚从 nib 中出来的视图图层,如 loadingview,尚未放入完整界面.

此外,这似乎是 CABasicAnimation,而不是 CAKeyframeAnimation。你需要解决这个问题。

您必须先加载 xib,然后在 ViewController 中的 viewDidAppear() 方法中调用 yourXib.awakeFromNib()

yourXib = Bundle.main.loadNibNamed("yourXib", owner: self, options: nil)?.first as! UIView
yourXib.awakeFromNib()