我有一个单例类,其他单例类或 utils 类通过它使用其中的属性。我正在使用 SwiftUI 中的切换元素,它需要一个绑定变量。如果我使用视图模型中的 @Published 变量或视图本身的 @State 变量,那么一切正常,但我希望使用单例类中的变量作为绑定变量。
我该怎么做?
class AppState {
static let shared = AppState()
private init() {}
private(set) var moduleState: ModuleState? = ModuleState.shared
}
class ModuleState {
static let shared = ModuleState()
private init() {}
var moduleState: ModuleState? = ModuleState()
var showDebugView: Binding<Bool> = .constant(false)
}
struct ContentView: View {
var body: some View {
VStack {
Toggle("Show Debug View",
isOn: AppState.shared.moduleState!.$showDebugView.wrappedValue)
.toggleStyle(SwitchToggleStyle(tint: .blue))
.frame(width: UIScreen.main.bounds.width - 50.0, height: 30.0)
}
}
}
使用上面的代码,我收到“‘ModuleState’类型的值没有成员‘$showDebugView’”错误。
如何将 showDebugView 作为绑定变量传递?
它已经是一个
Binding
. 您不需要使用从属性包装器中$
获取 aBinding
(就像使用 一样@State
)。你的代码可以是:
我在单例类中使用 Binding 的唯一原因是因为切换中的“isOn”需要它。我的应用程序不寻找切换的动态变化值。我找到了一种在切换本身内创建自定义绑定的方法。
如果有人来找的话,在这里分享代码: