Swift: 核心动画没有动画

Swift: Core Animation not animating

我是核心动画的新手。我正在尝试实现简单的动画,其中 UILabel 从 A 点移动到 B 点。我有以下从动画代码示例中获得的代码,但无法正常工作。标签根本不动。我做错了什么?

let frame = self.view.frame
let blueBox = UIView(frame: frame)
blueBox.backgroundColor = UIColor(red:  46/255, green: 83/255, blue: 160/255, alpha: 1.0)

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 400))
label.center = CGPoint(x: frame.size.width/2, y: frame.size.height/2)
label.textAlignment = .center
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0

label.layer.position = label.center

var attrsA = [NSFontAttributeName: UIFont(name: "LemonMilk", size: 92), NSForegroundColorAttributeName: UIColor.white]
var a = NSMutableAttributedString(string:"Hello\n", attributes:attrsA)
var attrsB =  [NSFontAttributeName: UIFont(name: "LemonMilk", size: 38), NSForegroundColorAttributeName: UIColor.white]
var b = NSAttributedString(string:"World", attributes:attrsB)
a.append(b)


label.attributedText = a

let theAnimation = CABasicAnimation(keyPath: "position");
theAnimation.fromValue = [NSValue(cgPoint: CGPoint(x: screenWidth/2, y: screenHeight/2))]
theAnimation.toValue = [NSValue(cgPoint: CGPoint(x: 100.0, y: 100.0))]
theAnimation.duration = 3.0;
theAnimation.autoreverses = false //true - reverses into the initial value either smoothly or not
theAnimation.repeatCount = 2

blueBox.addSubview(label)

view.addSubview(blueBox)
label.layer.add(theAnimation, forKey: "animatePosition");

首先:你不能同时调用label上的addSubviewlabel.layer上的add(animation:)。您只能为视图层次结构中 已经 的视图设置动画。换句话说,即使您的代码一切正常,您调用 add(animation:) 也太早了 。尝试引入一个 delay.

第二:这些行是伪造的:

theAnimation.fromValue = [NSValue(cgPoint: CGPoint(x: screenWidth/2, y: screenHeight/2))]
theAnimation.toValue = [NSValue(cgPoint: CGPoint(x: 100.0, y: 100.0))]

fromValuetoValue 都不能是 数组 。摆脱那些牙套。在 Swift 3.0.1 及更高版本中,您也不需要强制转换为 NSValue。所以:

theAnimation.fromValue = CGPoint(x: screenWidth/2, y: screenHeight/2)
theAnimation.toValue = CGPoint(x: 100.0, y: 100.0)

第三fromValue偶数是干什么用的?如果你想从标签已经存在的地方制作动画,只需省略 fromValue.

所以,我把你的代码修改成这样结束,我看到了动画:

label.attributedText = a
blueBox.addSubview(label)
view.addSubview(blueBox)
delay(1) {
    let theAnimation = CABasicAnimation(keyPath: "position");
    theAnimation.toValue = CGPoint(x: 100.0, y: 100.0)
    theAnimation.duration = 3.0;
    theAnimation.autoreverses = false //true - reverses into the initial value either smoothly or not
    theAnimation.repeatCount = 2
    label.layer.add(theAnimation, forKey: "animatePosition");
}