英文:
How do I prevent @State objects from being reset when the view temporarily disappears?
问题
我有状态对象,它们是从我的三个视图中的一个文件选择器设置的,比如在`View1`上。
```swift
@State private var fileName : String = ""
@State private var listFileURLs = [URL]()
@State private var selectedFileIndex = 0
当我切换到另一个视图然后返回时,状态对象似乎被重置了。视图的切换是基于按钮状态的if-else子句完成的。
if (showFirstView) {
View1()
} else if (showSecondView) {
View2()
}
我尝试将变量变为静态的,
@State static private var fileName : String = ""
@State static private var listFileURLs = [URL]()
@State static private var selectedFileIndex = 0
但奇怪的是,这导致这些变量在我启动文件选择器时没有更新。
我不能将这些变量移到超级视图,因为它们是由View1中的控件设置的。
我应该怎么做?
<details>
<summary>英文:</summary>
I have state objects which are set from a file picker on one of my three views, let's say on `View1`.
@State private var fileName : String = ""
@State private var listFileURLs = URL
@State private var selectedFileIndex = 0
When I switch over to another view and return, the state objects appear to be reset. The views are switched by an if-else clause based on button states
if (showFirstView) {
View1()
} else if (showSecondView) {
View2()
}
I tried turning the variables static,
@State static private var fileName : String = ""
@State static private var listFileURLs = URL
@State static private var selectedFileIndex = 0
But that strangely resulted in these variables not being updated when I launched the file picker.
I can't move these variables to the super View, because they are set by controls in View1.
How should I proceed?
</details>
# 答案1
**得分**: 1
可能的问题是每次更改 `showFirstView` 时都会创建一个新的视图。
您可以将 `@State` 变量从子视图移动到父视图,像这样:
```swift
import SwiftUI
struct ContentView: View {
@State private var showingFirstView = false
@State private var state1 = "文本"
@State private var state2 = "文本2"
var body: some View {
VStack {
if showingFirstView {
View1(state1: $state1)
} else {
View2(state2: $state2)
}
Button("切换视图") {
showingFirstView.toggle()
}
}
.padding()
}
}
struct View1: View {
@Binding var state1: String
var body: some View {
VStack {
TextEditor(text: $state1)
}
.padding()
}
}
struct View2: View {
@Binding var state2: String
var body: some View {
VStack {
TextEditor(text: $state2)
}
.padding()
}
}
英文:
Probably the problem is that you create a new View every time showFirstView
is changed.
You can move your @State
var from child view to parent view like this:
import SwiftUI
struct ContentView: View {
@State private var showingFirstView = false
@State private var state1 = "text"
@State private var state2 = "text2"
var body: some View {
VStack {
if showingFirstView {
View1(state1: $state1)
} else {
View2(state2: $state2)
}
Button("Switch view") {
showingFirstView.toggle()
}
}
.padding()
}
}
struct View1: View {
@Binding var state1: String
var body: some View {
VStack {
TextEditor(text: $state1)
}
.padding()
}
}
struct View2: View {
@Binding var state2: String
var body: some View {
VStack {
TextEditor(text: $state2)
}
.padding()
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论