Вы не должны получать доступ к другому представлению @State
:
Text("My Count: \(countView.count)")
Это гигантский красный флаг, указывающий, что вы делаете что-то не так. Вам нужен @Binding
здесь.
Вместо того, чтобы CountView
"владеть" count
, ContentView
должен иметь count
, потому что он должен показать его в Text
. ContentView
должен указать CountView
считать с ContentView.count
, используя @Binding
:
struct ContentView: View {
@State var count = 1
var body: some View {
VStack {
CountView(count: $count)
Text("My Count: \(count)")
Button("Show My Count"){print("\(self.count)")}
}
}
}
struct CountView: View {
@Binding var count: Int
var body: some View {
VStack {
Button("Increase count"){self.count += 1}
Text("Count = \(count)")
}
}
}