CABasicAnimation in Swift Playground

2019-02-17 03:57发布

问题:

Been going nuts trying to get a live view of an animation in a Swift Playground like in the WWDC "Swift Playgrounds" video. I tried to do a UIView.animateWithDuration with no luck so I am now trying to do a CABasicaAnimation because this seems to be what was used in the demo. I'be gotten rid of a lot of confusing errors and have imported the proper frameworks but am still having no luck getting my little circle to do anything but sit still in the center of my XCPShowView. Here is my code:

 import Foundation
 import XCPlayground
 import UIKit
 import QuartzCore

//Circle Button
class timerButtonGraphics: UIView {
    override func drawRect(rect: CGRect) {
        let colorGreen = UIColor(red: 0.310, green: 0.725, blue: 0.624, alpha: 1.000)
        let colorRed = UIColor(red: 241/255, green: 93/255, blue: 79/255, alpha: 100)
        var bounds = self.bounds
        var center = CGPoint()
        center.x = bounds.origin.x + bounds.size.width / 2
        center.y = bounds.origin.y + bounds.size.height / 2
        var radius = 61
        var path:UIBezierPath = UIBezierPath()
        path.addArcWithCenter(center, radius: CGFloat(radius), startAngle: CGFloat(0.0), endAngle: CGFloat(Float(M_PI) * 2.0), clockwise: true)
        path.strokeWithBlendMode(kCGBlendModeNormal, alpha: 100)
        path.lineWidth = 5
        colorGreen.setStroke()
        path.stroke()

        //Define the animation here
        var anim = CABasicAnimation()
        anim.keyPath = "scale.x"
        anim.fromValue = 1
        anim.toValue = 100
        anim.delegate = self
        self.layer.addAnimation(anim, forKey: nil)
    }
}

var test = timerButtonGraphics(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
test.setTranslatesAutoresizingMaskIntoConstraints(true)


XCPShowView("Circle Animation", test)`

回答1:

The first part of the solution is to enable the Run in Full Simulator option. See this answer for a step-by-step.

The second part of the solution is to contain your animated view in a container view, e.g.:

let container = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
XCPShowView("Circle Animation", container)
let test = timerButtonGraphics(frame: CGRect(x: 198, y: 0, width: 4, height: 400))
container.addSubview(test)

The third part of the solution is to correct your animation. The keyPath should be transform.scale.x instead of scale.x and you need to add a duration, e.g.:

anim.keyPath = "transform.scale.x"
anim.duration = 5

You should then be able to view the animation in your playground.