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

SwiftUI中如何同时使用Button的action与onTapGesture?

Button的action与onTapGesture冲突解决方案

问题出在SwiftUI的Button本身会拦截点击事件——当你给Button绑定了action闭包后,它会优先处理点击逻辑,并且阻止附加的.onTapGesture触发,这就是你的beginNow永远不会被修改的原因。

最简单的修复方案:合并逻辑到Button的action里

既然两个操作都是点击按钮时要执行的,直接把beginNow = true放到Button的action闭包里就行,完全不需要额外的.onTapGesture:

VStack {
    if beginNow {
        Rectangle()
            .frame(width: 200, height: 150)
    } else {
        Button(action: {
            tapped = true
            // 把原来手势里的逻辑移到这里
            beginNow = true
        }, label: {
            Text("Let's Begin!")
                .font(.title)
                .foregroundColor(.white)
                .padding()
                .background(Color.blue)
        })
        .scaleEffect(tapped ? 0 : 2)
        .animation(.easeOut(duration: 1), value: tapped)
    }
}

如果你确实需要区分手势(比如长按+点击)

如果之后有更复杂的手势需求(比如长按执行一个逻辑,点击执行另一个),可以用.simultaneousGesture让手势和Button的action同时响应:

Button(action: {
    tapped = true
}, label: {
    Text("Let's Begin!")
        .font(.title)
        .foregroundColor(.white)
        .padding()
        .background(Color.blue)
})
.scaleEffect(tapped ? 0 : 2)
.animation(.easeOut(duration: 1), value: tapped)
// 用simultaneousGesture替代onTapGesture
.simultaneousGesture(
    TapGesture().onEnded {
        beginNow = true
    }
)

不过回到你的场景,第一种合并逻辑的方案最直接也最符合SwiftUI的设计逻辑,没必要多此一举用手势。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 04:29:58