You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过UIButton自定义类为按钮点击动作添加通用延迟?

为CustomButton实现通用点击延迟效果

你可以通过重写CustomButton的sendAction(_:to:for:)方法来实现通用的点击延迟,所有绑定到该按钮的点击事件都会自动应用延迟,无需修改每个点击处理逻辑。

基础实现方案

直接在自定义按钮类中重写sendAction方法,将原动作延迟执行:

class CustomButton: UIButton {
    // 可自定义的延迟时间,默认0.4秒
    var tapDelay: TimeInterval = 0.4
    
    override func sendAction(_ action: Selector, to target: Any?, for event: UIEvent?) {
        DispatchQueue.main.asyncAfter(deadline: .now() + tapDelay) {
            super.sendAction(action, to: target, for: event)
        }
    }
}

这样不管是通过Storyboard绑定的IBAction,还是代码里用addTarget(_:action:for:)设置的点击事件,都会自动带上延迟效果。如果某个按钮需要不同的延迟时长,直接给该按钮实例设置tapDelay属性即可。

进阶:防止重复点击

如果需要避免用户在延迟期间重复点击导致多次触发动作,可以增加点击锁逻辑:

class CustomButton: UIButton {
    var tapDelay: TimeInterval = 0.4
    // 标记当前是否允许点击
    private var isTapAllowed: Bool = true
    
    override func sendAction(_ action: Selector, to target: Any?, for event: UIEvent?) {
        guard isTapAllowed else { return }
        
        isTapAllowed = false
        DispatchQueue.main.asyncAfter(deadline: .now() + tapDelay) {
            super.sendAction(action, to: target, for: event)
            // 延迟结束后恢复点击能力
            self.isTapAllowed = true
        }
    }
}

内容的提问来源于stack exchange,提问作者Pankaj Battise

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 20:15:00