【问题标题】:why is my custom UIButton subclass not triggering touch up IBAction?为什么我的自定义 UIButton 子类没有触发修饰 IBAction?
【发布时间】:2019-08-05 17:35:15
【问题描述】:

这可能与我在自定义子类中覆盖 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) 均无济于事。任何见解将不胜感激

【问题讨论】:

  • 另外,touchesBegan 的第一个参数在我调试时为空。也许这是另一个线索?

标签: swift


【解决方案1】:

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

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

【讨论】:

  • 感谢您的回复,我试过了,似乎我的覆盖 sendAction() 从未被调用过。为什么使用 sendAction 而不是 touchesBegan?
  • sendAction() 直接处理 UIButton 接收到触摸事件后执行的操作。也许检查以确保您将 UIButton 初始化为 myCustomButton?
【解决方案2】:

嗯,好的,想通了。在我的自定义按钮初始化程序中,我添加了一个子视图,默认情况下,将 userInteractionEnabled 设置为 true。在我的自定义按钮对象上设置userInteractionEnabled = true,在我的视图上设置userInteractionEnabled = false,然后将其添加为子视图允许我的自定义按钮捕获触摸并正确处理它,而不是捕获触摸的视图

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多