swift - 将 CABasicAnimation 添加到子类 UIButton - 如果启用

标签 swift uibutton autolayout subclass cabasicanimation

我在使用自动布局和子类 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中,它就可以正常工作。

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

最佳答案

尝试在 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)
    }
}

enter image description here

关于swift - 将 CABasicAnimation 添加到子类 UIButton - 如果启用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49100517/

相关文章:

iOS自定义带有动态内容的UIButton

ios - 我应该使整个层次结构的固有内容大小无效吗?

ios - iPhone X 将对象底部与安全区域对齐会破坏其他设备上的外观

ios - 有没有办法强制 Swift 中的 TextField 中的文本是非可选的?

Swift 3 RKObjectRequestOperation 返回错误,无法转换 RKObjectRequestOperation 类型

json - 我如何仅模拟 Alamofire 响应?

ios - 实例变量在 ViewDidLoad() 处重置为 nil

swift - 在 iPhone X 上以编程方式创建 UIButton 但安全区域问题

ios - iOS 中的 SWRevealViewController 项目

ios - 在实现自定义 View Controller 演示时,在哪里应用呈现 View 的约束?