如何在 SwiftUI 中将变量从一个视图传递到另一个视图 [英] How to pass variable from one view to another in SwiftUI
问题描述
我试图在 SwiftUI 中将一个变量从一个视图传递到另一个视图.我有一个重置按钮,我想在另一个视图中将变量设置为零.
I'm trying to pass one variable from one view to another in SwiftUI. I have a reset button in which I want to set the variable to zero in the other view.
我尝试在视图 1 中创建一个新结构并在视图 2 中访问该变量.
I have tried creating a new struct in view one and accessing that variable in view 2.
// View 1
@State var count = MyNumber.number
// Body of app
Button(action: {self.count = self.count-10}) {
Text("-")
}
Text("\(count)")
struct MyNumber {
static var number = 0
}
// View 2
@State var countit = MyNumber.number
// Body
Button(action: {self.countit = 0}) {
Text("Reset")
}
视图 1 中的文本仍显示在视图 1 中计算的数字
Text in view one is still showing the number that was computed in View 1
推荐答案
如果 View2
在 View1
中使用,你可以这样做:
If View2
is being used in View1
you could do something like this:
View1:
struct FirstView: View {
@State var count = 0
var body: some View {
VStack{
Text("\(self.count)")
Button(action:
{self.count = self.count-10})
{
Text("-")
}
SecondView(count: self.$count)
}
}
}
和View2:
struct SecondView: View {
@Binding var count: Int
var body: some View {
Button(action: {self.count = 0}) {
Text("Reset")
}
}
}
编辑
如果它们是完全不同的观点并且需要单一的事实来源,您可以使用 observableObject/EnvironmentVariables.最好的方法是将环境变量添加到 ContentView
中,它首先在 SceneDelegate
If they are completely different views and need single source of truth you could use an observableObject/EnvironmentVariables. The best way would be to add the environment variable to the ContentView
where it's first defined in the SceneDelegate
ContentView().environmentObject(SourceOfTruth())
这是 SourceOfTruth:
Here is SourceOfTruth:
class SourceOfTruth: ObservableObject{
@Published var count = 0
}
然后您可以将 EnvironmentObjects 用于其他视图:这是ContentView
:
Then you could use EnvironmentObjects to the other views:
Here is ContentView
:
struct ContentView: View {
@EnvironmentObject var truth: SourceOfTruth
var body: some View {
VStack {
FirstView()
SecondView()
}
}
}
这是FirstView
:
struct FirstView: View {
@EnvironmentObject var truth: SourceOfTruth
var body: some View {
VStack{
Text("\(self.truth.count)")
Button(action:
{self.truth.count = self.truth.count-10})
{
Text("-")
}
}
}
}
这是SecondView
:
struct SecondView: View {
@EnvironmentObject var truth: SourceOfTruth
var body: some View {
Button(action: {self.truth.count = 0}) {
Text("Reset")
}
}
}
这篇关于如何在 SwiftUI 中将变量从一个视图传递到另一个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!