我有一个单例类,其他单例类或 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
了。您不需要使用 $
从属性包装器中获取 Binding
(就像使用 @State
那样)。
您的代码可以是:
struct ContentView: View {
var body: some View {
VStack {
Toggle("Show Debug View",
isOn: AppState.shared.moduleState!.showDebugView)
.toggleStyle(SwitchToggleStyle(tint: .blue))
}
}
}