所以我有一个在类中声明的绑定变量:
@Binding var variableName: Bool
我在调用某个函数时返回一个视图。我想通过:
将注释传递到该视图中return CustomView(variableName: $variableName)
这是正确的吗?我不确定。另外,在视图本身内部,我不完全确定如何正确进行初始化。最终目标是能够从视图的函数访问variableName的值。无论如何,我尝试在CustomView类中声明以下内容:
@Binding var variableName: Bool
对于初始化,我不确定是否应该将变量名称传递给参数(如果应该,我不确定如何。我也不知道是否应该以self.variableName进行初始化。 = value ...只是要清楚一点,目标是在初始化后访问variableName的值。如果我可以添加更多代码以使其更易于理解,请告诉我!
尚不清楚您要实现什么,但是请看下面的代码:
import SwiftUI
struct ParentView: View {
@Binding var customVariable: Bool
var body: some View {
VStack {
Toggle(isOn: $customVariable) {
Text("Show/Hide Custom View")
}
if $customVariable.wrappedValue {
CustomView(customVariable: $customVariable)
}
}
}
}
struct CustomView: View {
@Binding var customVariable: Bool
init(customVariable: Binding<Bool>) { // You don't need an initializer here, it is just to demonstrate how you can use it for Binding values
_customVariable = customVariable
}
var body: some View {
Text("Custom View")
}
}
但是,可以在SwiftUI中更好地协调模型和视图的方法如下:
import SwiftUI
class CustomModel: ObservableObject {
@Published var shouldShowCustomView: Bool = false
}
struct ParentView: View {
@ObservedObject var model: CustomModel
var body: some View {
VStack {
Toggle(isOn: $model.shouldShowCustomView) {
Text("Show/Hide Custom View")
}
if model.shouldShowCustomView {
CustomView()
.environmentObject(model)
}
}
}
}
struct CustomView: View {
@EnvironmentObject var model: CustomModel
var body: some View {
Text("Custom View")
}
}
因此,可以将Binding
与ObservableObject
值一起使用,而不是Published
。