SwiftUI: 如何在不调用该视图的情况下从另一个视图更改@State的值

huangapple go评论50阅读模式
英文:

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&#39;s action works.

</details>



huangapple
  • 本文由 发表于 2023年2月8日 09:12:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75380503.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定