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

SwiftUI中用@ObservedObject数据替换@State Binding<Int>实现confettiCannon

解决ConfettiSwiftUI绑定@ObservedObject属性的问题

问题原因

你遇到的错误是因为game.counter如果是普通Int属性,SwiftUI无法自动为其生成Binding<Int>——只有被@Published修饰的ObservableObject属性,或者手动构建的Binding才能满足组件的参数要求。

解决方案1:将counter改为@Published属性

如果Game类是你可控的,直接给counter添加@Published修饰符,这样SwiftUI会自动为其生成Binding:

class Game: ObservableObject {
    @Published var counter = 0 // 添加@Published修饰符
}

之后在视图中直接使用$game.counter即可:

confettiCannon(counter: $game.counter)

解决方案2:手动构建Binding(无法修改Game类时)

如果无法修改Game类的代码,通过Binding的构造器手动创建绑定,明确指定读取和写入逻辑:

confettiCannon(counter: Binding(
    get: { game.counter },
    set: { game.counter = $0 }
))

这种方式同样能满足组件对Binding<Int>的参数要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:50:28