CAKeyframeAnimation无法在nib中工作

时间:2017-02-21 09:45:42

标签: ios swift animation cakeyframeanimation

我有一个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
    }

2 个答案:

答案 0 :(得分:0)

您无法在awakeFromNib中开始制作动画。太早了。您只能为实际位于界面的视图/图层层次结构中的图层设置动画,并且刚刚从笔尖出来的视图图层(如loadingview)尚未完整放置界面还没有。

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

答案 1 :(得分:0)

你必须首先加载xib,然后在ViewDid中查看viewDidAppear()方法,只需调用yourXib.awakeFromNib()

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