2014-12-05 77 views
3

如何使用swift動畫UILabel的顏色變化?我看到有人提到使用CALayer,但我無法弄清楚Swift語法。在Swift中動畫UILabel文本顏色

這是Objective-C中的一個例子

CALayer *layer = myView.layer; 
CATextLayer *textLayer = [CATextLayer layer]; 
[textLayer setString:@"My string"]; 
[textLayer setForegroundColor:initialColor; 
[textLayer setFrame:self.bounds]; 
[[self.view layer] addSublayer:textLayer]; 

[UIView animateWithDuration:0.5 animations:^{ 
    textLayer.foregroundColor = finalColor; 
    }]; 
+0

我編輯我原來的問題,包括Objective-C的 – user3250926 2014-12-05 18:28:09

回答

11

它比與CALayer的工作

let myLabel: UILabel! 

UIView.animateWithDuration(2, animations: {() -> Void in 
    myLabel.backgroundColor = UIColor.redColor(); 
}) 

那它更容易...

編輯

好吧,對不起,我不知道你想要改變什麼顏色E. ..我已經將您爲例,SWIFT代碼...

第一

import QuartzCore 

if let layer: CALayer = self.view.layer as CALayer? { 
    if let textLayer = CATextLayer() as CATextLayer? { 
     textLayer.string = "My string" 
     textLayer.foregroundColor = UIColor.whiteColor().CGColor 
     textLayer.frame = self.view.bounds 
     self.view.layer.addSublayer(textLayer) 

     UIView.animateWithDuration(0.5, animations: {() -> Void in 
      textLayer.foregroundColor = UIColor.redColor().CGColor 
     }) 
    } 
} 
+1

的例子請投我了,如果它幫助你... – 2014-12-05 18:23:40

+0

的文本顏色的變化,但它不生動。它瞬間改變。 – user3250926 2014-12-05 18:29:25

+1

backgroundColor≠textColor,並且如問題的作者指出的那樣,這實際上並不工作 – 2014-12-05 18:34:54

1

使用迅速,我的分機動畫的UILabel的顏色或文字的變化。

extension UILabel { 
    /** 
    Set Text With animation 

    - parameter text:  String? 
    - parameter duration: NSTimeInterval? 
    */ 
    public func setTextAnimation(text: String? = nil, color: UIColor? = nil, duration: NSTimeInterval?, completion:(()->())? = nil) { 
     UIView.transitionWithView(self, duration: duration ?? 0.3, options: .TransitionCrossDissolve, animations: {() -> Void in 
      self.text = text ?? self.text 
      self.textColor = color ?? self.textColor 
      }) { (finish) in 
       if finish { completion?() } 
     } 
    } 
} 

使用顏色:

self.label.setTextAnimation(color: UIColor.whiteColor(), duration: 0.15)