2017-02-03 110 views
0

當談到Core Animation時,我是一個noobie。我試圖實現簡單的動畫,其中UILabel從A點移動到B點。我從動畫代碼示例中獲得以下代碼,但無法使其工作。標籤根本不會移動。我究竟做錯了什麼?Swift:核心動畫沒有動畫效果

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

這可能是一個更容易讓你只使用'UIView.animate(withDuration:)' – Pierce

+0

@Pierce但那不回答問題 – matt

+0

@matt - 我知道這就是爲什麼我沒有回答這個問題。我只是在評論中提出建議 – Pierce

回答

1

首先:你不能在labeladd(animation:)label.layer相提並論調用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))] 

既不fromValue也不toValue可以是陣列。擺脫這些大括號。而在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"); 
} 
+0

我認爲動畫仍然不會做你想做的事情,但至少在這些建議中你應該看到一些事情發生。如果沒有,請讓我知道。 – matt