我在使用自动布局和子类 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)
}
}
关于swift - 将 CABasicAnimation 添加到子类 UIButton - 如果启用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49100517/