2016-10-01 51 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,并在单击该按钮时在标签上执行动画。虽然这种方法看起来有些“黑客”,但好处是在标签动画时按钮不会被禁用,这意味着您可以注册快速顺序按钮按钮(尽管按钮的用途看起来像是登录用户,在这种情况下,这可能不需要你)。