2017-02-03 5 views
0

Core Animationについては、私はnoobieです。 UILabelがポイントAからポイントBに移動するシンプルなアニメーションを実装しようとしています。私はアニメーションコードの例から得た次のコードを持っていますが、これを動作させることはできません。ラベルは単に移動しません。私は間違って何をしていますか?Swift:Core Animationがアニメ化しない

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"); 
+2

(withDurationを:)' – Pierce

+0

@Pierceが、それは質問に答えていません – matt

+0

@matt - 私はそれが私がそれに答えなかった理由を知っています。私はコメントの中でちょっとお勧めしました – Pierce

答えて

1

まず:あなたは、同じ息でlabel.layerlabeladd(animation:)addSubviewを呼び出すことはできません。ビュー階層内ののビューは、すでににのみアニメートできます。言い換えれば、あなたのコードに関するすべてがうまくいたとしても、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を省略します。

したがって、私はこのように終了するようにコードを修正し、私はアニメを見た:あなたがちょうど `UIView.animate使用するためにはるかに簡単であるかもしれない

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"); 
} 
+0

アニメーションはまだあなたがしたいことをしません、私は思いますが、少なくともそれらの提案では何かが起こるべきであると思います。そうでない場合は、私に知らせてください。 – matt

関連する問題