2016-10-01 53 views
0

我試圖改變使用交叉溶解動畫的按鈕背景的顏色,但是,每當我運行它時,它立即改變顏色而不是平滑過渡。Cross-Disolve轉換隻是立即改變 - Swift 3.0

UIView.transition(with: self.SignIn, 
        duration:3, 
        options: UIViewAnimationOptions.transitionCrossDissolve, 
        animations: { self.SignIn.backgroundColor? = UIColor(hexaString: "#" + hex) }, 
        completion: nil) 

回答

3

而不是設置在backgroundColoranimations我所認爲transition之前設置它,然後開始看transition,它會很好地工作的。

self.btnAnimate.backgroundColor = UIColor.red 
UIView.transition(with: self.btnAnimate, 
        duration: 3, 
        options: .transitionCrossDissolve, 
        animations: nil, 
        completion: nil) 

輸出

enter image description here

注:我已經設置red顏色backgroundColor你可以設置什麼都顏色,你想要的。

+0

謝謝!當我在我的筆記本電腦上時,我會對此進行測試。 –

+0

完美的作品! –

+0

歡迎伴侶:) –

0

發生這種情況是因爲您的動畫與默認按鈕動畫衝突。

爲了解決這個問題,你可以創建一個自定義子類的UIButton的:

import UIKit 

import UIKit 

class CustomButton: UIButton { 

    func animateButton(hex: String) { 

     // This block disables the default animations 
     UIButton.performWithoutAnimation { 

      // This is where you define your custom animation 
      UIView.transition(with: self, duration:3, options: UIViewAnimationOptions.transitionCrossDissolve, animations: { 
       self.backgroundColor? = UIColor(hexaString: "#" + hex) }, completion: nil) 

      // You must call layoutIfNeeded() at the end of the block to prevent layout problems 
      self.layoutIfNeeded() 
     } 
    } 

} 

然後調用這個函數:

signInButton.animateButton("ffffff") // Pass in your hex string 

當然,一定要改變你的loginButton的類在故事板上從UIButtonCustomButton

這種方法的缺點是在動畫過程中文本仍然變暗。可能有一種方法可以覆蓋這個(我無法快速確定如何),所以此解決方案的另一種方法是使用UILabel而不是UIButton並設置點擊監聽器。

或者您可能需要考慮的另一種方法是在UIButton後面放置一個customLabel,並在單擊該按鈕時在標籤上執行動畫。雖然這種方法看起來有些「黑客」,但好處是在標籤動畫時按鈕不會被禁用,這意味着您可以註冊快速順序按鈕按鈕(儘管按鈕的用途看起來像是登錄用戶,在這種情況下,這可能不需要你)。