iosswiftanimationcakeyframeanimation

CAKeyframeAnimation not working in nib


I have a nib file that has to animate a view to move in a circular path. But when I run my code I see the view was not animated and at the top corner of my view

this is my code

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
    }

Solution

  • You cannot begin an animation in awakeFromNib. It is too soon. You can only animate a layer that is actually in your interface's view/layer hierarchy, and a layer of a view that has just come out of the nib, like loadingview, has not been placed into the full interface yet.

    Also, this would appear to be a CABasicAnimation, not a CAKeyframeAnimation. You need to fix that.