【问题标题】:Execute a method every time a tap is done in a button每次点击按钮时执行一个方法
【发布时间】:2019-11-28 18:47:14
【问题描述】:

我的 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)

    }
}

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

我应该对此进行什么修改,以便在您点击按钮时对班级本身发生这种情况? 或者,换一种说法,我怎样才能覆盖所有 UIButtons 通用的“onClick”方法,以便在点击时它们都会自动闪烁?

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

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

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

【问题讨论】:

    标签: ios swift user-interface uibutton


    【解决方案1】:

    你需要创建一个类似的子类

    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 中的任何按钮类

    【讨论】:

    • 这正是我所需要的。但这对我不起作用。首先,我有一个错误指出“方法不会覆盖其超类中的任何方法”。我还在 touchesBegan 中添加了一条打印语句并删除了“override”关键字,但没有任何效果。
    • 嘿。谢谢!有了你分享的东西,我能够完成它。我会为 Swift 4 添加正确的签名。
    【解决方案2】:

    容易多了 -

    @IBAction func keyPressed(_ sender: UIButton) {
      //button Title is sound.wav filename
      playSound(soundName: sender.currentTitle!) 
      //Reduces the sender's (the button that got pressed) opacity to half.
      sender.alpha = 0.5
      //the following Code should execute after 0.2 second delay.
      DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
        //Bring's sender's opacity back up to fully opaque, thus completing the "blink" effect on press
        sender.alpha = 1.0
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-30
      • 2020-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多