SwiftUI–尝试将操作表可见性绑定到已发布的var属性



我是SwiftUI的新手。这是我使用它创建的第一个应用程序。

我有这个代码:

class ActionSheetViewControl {
enum ActionSheetType {
case none
case controlForm
case suggestionForm
case negativeForm
}
var type:ActionSheetType = .none
var showActionSheet = false
var shouldShowActionSheet:Bool {
get {
return showActionSheet && ((type == .controlForm) || (type == .suggestionForm))
}
}
}

表单应该只显示两种表单。

然后我在ContentView 上有这个

class GlobalVariables: ObservableObject {
@Published var actionControl: ActionSheetViewControl = ActionSheetViewControl()
}

@EnvironmentObject var globalVariables : GlobalVariables
// on body
.sheet(isPresented: XXXX,
onDismiss: {

}) {
}

我在XXXX上穿什么?

我试过

globalVariables.actionSheetViewControl.shouldShowActionSheet

以及

globalVariables.actionSheetViewControl.$shouldShowActionSheet

$globalVariables.actionSheetViewControl.shouldShowActionSheet

我得到这个错误:

Cannot convert value of type 'Bool' to expected argument type 'Binding<Bool>'

您必须将ActionSheetViewControl更改为struct,因此它是一种值类型。

struct ActionSheetViewControl {

然后在您的ContentView中,按如下方式使用它:

struct ContentView: View {
@EnvironmentObject var globalVariables : GlobalVariables
var body: some View {
Button(action: {
globalVariables.actionControl.showActionSheet = true
})
{
Text("Open")
}

Text("Test")
.sheet(isPresented: $globalVariables.actionControl.showActionSheet, content: {
Text("Sheet")
})
}

}

相关内容

最新更新