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

iOS按钮动画执行时,如何强制停止并解锁按钮交互?

解决UIButton动画期间无法响应重复触摸的问题

问题根源

  • 动画未添加.allowUserInteraction选项,导致执行动画时系统屏蔽了UIButton的触摸事件
  • 仅调用removeAllAnimations但未同步视图的实际显示状态,导致视图状态混乱,无法正确触发新的动画及逻辑

修复方案

1. 更新动画函数,添加交互允许并重置视图状态

修改你的两个动画函数,在启动新动画前先中断现有动画、同步视图到当前显示状态,同时添加允许用户交互的选项:

func animateDownFloat(_ viewToAnimate: UIView, duration: Double = 0.2) {
    // 中断当前所有动画,同步视图到屏幕显示的实时状态
    viewToAnimate.layer.removeAllAnimations()
    if let presentationLayer = viewToAnimate.layer.presentation() {
        viewToAnimate.transform = presentationLayer.transform
    }
    
    UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.2, options: [.curveLinear, .allowUserInteraction], animations: {
        viewToAnimate.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
    })
}

func animateUpFloat(_ viewToAnimate: UIView, duration: Double = 0.15) {
    viewToAnimate.layer.removeAllAnimations()
    if let presentationLayer = viewToAnimate.layer.presentation() {
        viewToAnimate.transform = presentationLayer.transform
    }
    
    UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: [.curveLinear, .allowUserInteraction], animations: {
        viewToAnimate.transform = CGAffineTransform(scaleX: 1, y: 1)
    })
}

2. 保留原有IBAction逻辑

你的numberButtonTouchedDown和numberButtonTouchedUp无需额外修改,动画函数更新后,每次触发时都会先清理旧动画并重置状态,再启动新动画,同时按钮在动画期间能正常接收触摸事件。

原理说明

  • .allowUserInteraction:让UIView在执行动画时不阻止用户交互,确保触摸事件能正常触发
  • presentationLayer:获取当前屏幕上显示的视图中间状态,将视图的transform同步到该状态,避免直接移除动画后视图跳回初始位置,同时让新动画从当前显示位置平滑过渡

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 11:20:57