ios - 每次在按钮中完成点击时执行一个方法

标签 ios swift user-interface uibutton

我的 Swift 按钮中有以下扩展:

extension UIButton {
    func backgroundChange() {
        let colorAnimation = CABasicAnimation(keyPath: "backgroundColor")
        colorAnimation.duration = 0.3
        colorAnimation.isAdditive = true
        colorAnimation.fromValue = UIColor.black.cgColor
        colorAnimation.toValue = self.layer.backgroundColor
        colorAnimation.repeatCount = 1
        colorAnimation.autoreverses = true
        layer.add(colorAnimation, forKey: nil)

    }
}

这基本上只是在按钮中触发“闪光”动画。问题是,每次我希望这种情况发生时,我都必须手动调用此方法。

我应该对此进行哪些修改,以便在您点击按钮时类本身会发生这种情况? 或者,换句话说,我如何覆盖所有 UIButton 通用的“onClick”方法,以便它们在点击时自动闪烁?

编辑:用户已将此问题标记为重复。但它不是。他们链接的问题根本没有回答我的问题。

我找到了正确的方法。这是要走的路:

override func touchesBegan(_ touches: Set<UITouch>, with: UIEvent?){
        backgroundChange()
        super.touchesBegan(touches as! Set<UITouch>, with: with)
    }

最佳答案

你需要像这样创建一个子类

class CustomButton: UIButton {

override func touchesBegan(_ touches: Set<UITouch>, with: UIEvent?){
    backgroundChange()
    super.touchesBegan(touches as! Set<UITouch>, with: with)
}

func backgroundChange() {
    let colorAnimation = CABasicAnimation(keyPath: "backgroundColor")
    colorAnimation.duration = 0.3
    colorAnimation.isAdditive = true
    colorAnimation.fromValue = UIColor.black.cgColor
    colorAnimation.toValue = self.layer.backgroundColor
    colorAnimation.repeatCount = 1
    colorAnimation.autoreverses = true
    layer.add(colorAnimation, forKey: nil)

 }
}

然后将其分配给 IB 中的任何按钮类

关于ios - 每次在按钮中完成点击时执行一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59094789/

相关文章:

ios - HKHealthStore deleteObjects 报错 Domain=com.apple.healthkit Code=100 "Transaction failure."

swift - DetailViewControllers 内容被截断

user-interface - 声明式与编程式 UI(对象实例、XAML、MXML、XUL 等)

user-interface - 统一更改下拉菜单的大小

ios - 如何在任何 UICollectionViewCell 下方插入随机 View

ios - 回调 swift 3 中的标签未更改

ios - gdb 远程返回错误 e08

ios - 无法将存档导出到 ipa(未找到适用的设备)

ios - 使用 SwiftUI 从结构中的完成变量调用方法

iphone - 如何使用 UIPanGestureRecognizer 中的 velocityView 加快拖动速度?