2016-12-15 60 views
1

我想爲我的UIButtons的backgroundColor屬性設置動畫,但我不確定從哪裏開始。我從來沒有使用過Core Animation,我不確定我是否需要這麼基本的東西?在iOS中使用Swift3爲UIButton設置'backgroundColor'的動畫

我風格使用類和看起來像這樣的方法的按鈕:

redTheme.swift

func makeRedButton() {  
     self.layer.backgroundColor = myCustomRedcolor 
    } 

回答

5

您可以UIView Animation爲以下做:

注意:只要不要忘記在執行動畫之前清除背景,否則它將無法工作。那是因爲動畫需要一個起點和終點,起點是對紅色的清晰顏色。或者將alpha 0轉換爲alpha 1或者反過來。

let button = UIButton(frame: CGRect(x: 0, y: 100, width: 50, height: 50)) 
button.layer.backgroundColor = UIColor.clear.cgColor 
self.view.addSubview(button) 

     func makeRedButton() { 

      UIView.animate(withDuration: 1.0) { 
       button.layer.backgroundColor = UIColor.red.cgColor 
      } 

     } 
+0

完美謝謝! – Brewski

0

出於某種原因,動畫button.layer.backgroundColor 過零效果爲我定製的UIButton所以我的動畫阿爾法像這樣:

func provideVisualFeedback(_ sender:UIButton!) 
{ 
    sender.backgroundColor = UIColor.whatever 
    sender.alpha = 0 
    UIView .animate(withDuration: 0.1, animations: { 
     sender.alpha = 1 
    }, completion: { completed in 
     if completed { 
      sender.backgroundColor = UIColor.white 
     } 
    }) 
} 

然後

@IBAction func buttonAction(_ sender:NumberPadButton!) 
{ 
    provideVisualFeedback(sender) 
    do your thing once animation was setup with the helper above