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

SwiftUI如何在点击其他按钮或按钮点击10次时修改其动作与属性

实现逻辑

SwiftUI 是声明式 UI 框架,不需要主动获取按钮的引用就能修改属性,所有按钮的文本、触发动作都直接和状态变量绑定,修改状态值就会自动更新 UI 表现,刚好可以同时解决你的两个需求。

步骤1:新增状态变量

在当前 View 的结构体中新增两个状态变量:

// 记录按钮累计点击次数
@State private var tapCount = 0
// 标记按钮是否切换为重启模式
@State private var isRestartMode = false

步骤2:修改按钮逻辑

按钮的点击动作、文本、样式全部根据状态判断:

Button(action: {
    if isRestartMode {
        // 重启逻辑:按需重置所有游戏状态
        tapCount = 0
        isRestartMode = false
        roundTracker = 0
        scoreTracker = 0
        game.target = Int.random(in: 1...100)
    } else {
        alertIsVisible = true
    }
}) {
    Text(isRestartMode ? "重启游戏" : buttonText)
        .fontWeight(.bold)
        .padding()
        // 切换模式时同步修改背景色做区分,不需要可以删掉
        .background(isRestartMode ? Color.red : Color.blue)
        .foregroundColor(.white)
        .cornerRadius(20)
}
.alert(isPresented: $alertIsVisible, content: {
    let roundedValue = Int(sliderValue.rounded())
    let points = game.points(sliderValue: roundedValue)
    
    return Alert(title: Text("Hello!"), message: Text("The slider's value is \(roundedValue).\n" + "You scored \(points) points this round"), dismissButton: .cancel(
        {
            game.target = Int.random(in: 1...100)
            roundTracker += 1
            scoreTracker += points
            // 弹窗关闭后累计点击次数+1
            tapCount += 1
            // 点击满10次切换为重启模式
            if tapCount >= 10 {
                isRestartMode = true
            }
        }
    ))
})

无名称按钮的属性修改说明

你不需要像 UIKit 那样给按钮设置变量名、获取实例再修改属性,SwiftUI 所有 UI 元素的属性都是声明时绑定到状态变量的,只要修改对应的状态值,UI 会自动刷新。比如上面的按钮文本、背景色、点击动作都是绑定到isRestartMode状态,状态变更后按钮会自动更新,不需要额外引用按钮实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 09:09:05