英文:
SwiftUI: How to change the value of an @State from another view without calling said view
问题
我有三个文件:文件A,文件B和文件C。
我想要从文件B中更改文件C中的@State的值,但我更希望实际上是从文件A中运行文件C的视图。
以下是我的文件和代码,以帮助人们理解问题:
文件A:
```swift
import SwiftUI
struct ContentView: View {
var body: some View {
FileC()
}
}
文件B:
import SwiftUI
struct FileB: View {
var body: some View {
Button(action: {
variable = true // 这是我想要改变的变量。
}) {
Image("Image")
}
}
}
文件C:
import SwiftUI
struct FileC: View {
@State var variable = false
var body: some View {
if variable == true {
Rectangle()
}
}
}
我还没有尝试任何可以解决这个问题的方法,因为我在Swift方面经验有限,不知道在这种情况下该怎么做。我希望能够从文件B中访问变量,例如使用FileB().variable = true
,但这只给我各种错误或根本没有任何作用。
我从其他来源阅读到可以在调用视图时使用@Binding作为参数,但我希望能够在所选文件中调用该函数时不需要该信息。
<details>
<summary>英文:</summary>
I have three files: File A, File B and File C.
I want to change the value of an @State in File C *from* File B, but I would prefer to actually run the view in File C *from* File A.
Here are my files and code to help people understand the issue:
File A:
#import SwiftUI
struct ContentView: View {
var body: some View {
FileC()
}
}
File B:
#import SwiftUI
struct FileB: View {
var body: some View {
Button (action: {
variable = true // This is the variable I want to change.
})
{
Image("Image")
}
}
}
File C:
#import SwiftUI
struct FileC: View {
@State var variable = false;
var body: some View {
if variable == true {
Rectangle()
}
}
}
I have not tried anything that would resolve this issue as I have little experience in Swift and do not know what to do in this case. I hoped to access the variable from file B with something such as ```FileB().variable = true```, but this only gave me various errors or did nothing at all.
I have read from other sources to use @Binding as an argument for when calling a view, but I want to be able to call the function *without* having that information available from the chosen file.
</details>
# 答案1
**得分**: 1
A source of truth, eg @State, needs to be in a common parent of all the Views it is needed. Pass down read access as let or write access as @Binding var.
要传递数据到层次结构的上层,请查看 Preferences。
Another feature is to use closures, like how Button's action works.
<details>
<summary>英文:</summary>
A source of truth, eg @State, needs to be in a common parent of all the Views it is needed. Pass down read access as let or write access as @Binding var.
To pass data up the hierarchy look at Preferences.
Another feature is to use closures, like how Button's action works.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论