【问题标题】:Adding a CABasicAnimation to a subclassed UIButton - if enabled将 CABasicAnimation 添加到子类 UIButton - 如果启用
【发布时间】:2018-08-12 12:30:45
【问题描述】:

我在使用 Autolayout 和子类 UIButton 时遇到问题。在我的 UIButton 子类中,我重写 isEnabled 以在启用按钮时添加彩色动画。见下文。

// Within my subclassed button:
override var isEnabled:Bool {
    didSet {
        UIChanges.colorButton(buttonToFade: self)
    }
}

// colorButton to be called from UIChanges:
static func colorButton(buttonToFade:UIView) {
    let colorAnimation = CABasicAnimation(keyPath: "backgroundColor")
    colorAnimation.duration = 1
    colorAnimation.fromValue = UIColor.black.cgColor
    colorAnimation.toValue = UIColor.white.cgColor
    colorAnimation.repeatCount = 10
    colorAnimation.autoreverses = true
    buttonToFade.layer.add(colorAnimation, forKey: nil)
}

问题是,这个动画永远不会出现。

如果启用此 colorButton() 动画,如何将其添加到子类按钮?

我认为这与自动布局有关,因为如果我将该功能放在 layoutSubviews 中,它就可以正常工作。

编辑: 我向视图控制器添加了一个新按钮,该按钮手动将子类按钮更改为启用,@JD.答案工作正常(CABasicAnimation 触发)。但是,如果未按下该测试仪按钮,CABasicAnimation 不会触发。我试图调整的这个按钮主要在 AppDelegate 中启用 - 那么这可能是问题的原因吗?按钮设置为启用时未加载按钮框架?自动布局问题?

【问题讨论】:

    标签: swift uibutton autolayout subclass cabasicanimation


    【解决方案1】:

    尝试在 UIView 或 CALayer Extension 中添加动画代码,然后从自定义 UIButton 调用函数。

    class CustomButton: UIButton {
    
        override var isEnabled:Bool {
            didSet {
                if isEnabled {
                    setTitle("Enable", for: .normal)
                    layer.colorButton()
                } else {
                    setTitle("Disable", for: .normal)
                    layer.removeAllAnimations()
                }
            }
        }
    }
    
    extension CALayer {
    
        func colorButton() {
            let colorAnimation = CABasicAnimation(keyPath: "backgroundColor")
            colorAnimation.duration = 1
            colorAnimation.fromValue = UIColor.black.cgColor
            colorAnimation.toValue = UIColor.white.cgColor
            colorAnimation.repeatCount = 10
            colorAnimation.autoreverses = true
            add(colorAnimation, forKey: nil)
        }
    }
    

    【讨论】:

    • 还是什么都没有。启用按钮时不出现动画。
    • 您是否在 Identity Inspector 中分​​配了子类?
    • 是的,我已将其设置为 Identity Inspector 中的子类按钮类。我编辑了我的问题。如果我有一个单独的按钮可以更改子类按钮状态以启用,那么您的答案可以正常工作。如果我没有那个按钮(就像在你的动画中一样),它就不起作用。可能是因为在 AppDelegate didFinishLaunchingWithOptions 中启用了这个按钮吗?没有为 CABasicAnimation 设置按钮框架?自动布局问题?
    • 没有。您也可以从应用委托启用。
    猜你喜欢
    • 1970-01-01
    • 2011-10-04
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    • 2010-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多