首页 > 解决方案 > 为什么我的自定义 UIButton 子类没有触发修饰 IBAction?

问题描述

这可能与我在自定义子类中覆盖 touchesBegan 的事实有关:

class myCustomButton: UIButton {

override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        print("TOUCHES BEGAN OVERRIDE CALLED")
        originalColor = self.backgroundColor ?? .red
        self.backgroundColor = .white
        self.animateScale()
        setNeedsDisplay()
    }
//...
}

touchesEnded 类似地被覆盖,并且这两个函数都被调用并在按钮按下时将调试语句打印到控制台。但是,从我的视图控制器中按下的按钮 IBAction 中的代码永远不会运行

@IBAction func nextButtonPressed(_ sender: Any) {  
    print("this is never executed")
    //...
}

我仔细检查了 IBOutlet 没有损坏,并将 (_ sender: Any) 更改为 (_ sender: AnyObject) 均无济于事。任何见解将不胜感激

标签: swift

解决方案


尝试覆盖 UIButton 的 sendAction 函数,而不是覆盖 touchesBegan:

override func sendAction(_ action: Selector, to target: Any?, for event: UIEvent?) {
    super.sendAction(action, to: target, for: event)
    //Insert your code here
}

推荐阅读