Cross-Disolve转换立即改变 - Swift 3.0

时间:2016-10-01 07:33:43

标签: swift swift3 uiviewanimation uiviewanimationtransition

我尝试使用交叉溶解动画来改变按钮背景的颜色,但是,每当我运行它时,它会立即改变颜色而不是平滑过渡。

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

2 个答案:

答案 0 :(得分:3)

我没有在backgroundColor块中设置animations,而是在视图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,您可以设置所需的颜色。

答案 1 :(得分:0)

这是因为您的动画与默认按钮动画冲突。

要解决此问题,您可以创建UIButton的自定义子类:

 select * from yourtable
 where UserId like '%,' + idtocheck + ',%' or
 UserId like  idtocheck + ',%' or
 UserId like '%,' + idtocheck  or
 UserId = idtocheck  

然后调用此函数:

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()
        }
    }

}

当然,请务必将故事板上的loginButton类从signInButton.animateButton("ffffff") // Pass in your hex string 更改为UIButton

这种方法的缺点是在动画过程中文本仍然变暗。可能有一种方法可以覆盖它(我无法快速确定如何),因此该解决方案的另一种方法是使用UILabel而不是UIButton并设置on click侦听器。

或者您可能要考虑的另一种方法是将customLabel放在UIButton后面,并在单击按钮时在标签上执行动画。虽然这种方法看起来有点“hacky”,但优点是在标签动画时不会禁用按钮,这意味着您可以注册快速顺序按钮按下(虽然看起来按钮的目的是记录用户,在这种情况下,你可能不需要这样做。)