@State变量不存储价值



我的目标是在视图之间传递值,从Chooser到ThemeEditor。当用户按下一个图标时,我保存我想传递的对象,然后使用sheet并传递包含@State var内容的新创建的视图。

sheet

中创建ThemeEditor视图时,成功地分配给@State var themeToEdit,但是它是nil

。我做错了什么?

struct Chooser: View {
@EnvironmentObject var store: Store

@State private var showThemeEditor = false
@State private var themeToEdit: ThemeContent?
@State private var editMode: EditMode = .inactive
@State private var isValid = false

var body: some View {

NavigationView {
List {
ForEach(self.store.games) { game in
NavigationLink(destination: gameView(game))
{
Image(systemName: "wrench.fill")
.imageScale(.large)
.opacity(editMode.isEditing ? 1 : 0)
.onTapGesture {
self.showThemeEditor = true
/* themeInfo is of type struct ThemeContent: Codable, Hashable, Identifiable */
self.themeToEdit = game.themeInfo 
}
VStack (alignment: .leading) {
Text(self.store.name(for: something))

HStack{
/* some stuff */
Text(" of: ")
Text("Interesting info")
}
}
}
}
.sheet(isPresented: $showThemeEditor) {
if self.themeToEdit != nil { /* << themeToEdit is nil here - always */
ThemeEditor(forTheme: self.themeToEdit!, $isValid)
} 
}
}
.environment(.editMode, $editMode)
}
}
}

struct ThemeEditor: View {
@State private var newTheme: ThemeContent
@Binding var isValid: Bool
@State private var themeName = ""

init(forTheme theme: ThemeContent, isValid: Binding<Bool>) {
self._newTheme = State(wrappedValue: theme)
self._validThemeEdited = isValid
}
var body: some View {
....
}
}
struct ThemeContent: Codable, Hashable, Identifiable {
/* stores simple typed variables of information */
}

.sheet内容视图是在创建时捕获的,因此如果您想要检查其中的内容,则需要使用.sheet(item:)变体,如

.sheet(item: self.$themeToEdit) { item in
if item != nil {
ThemeEditor(forTheme: item!, $isValid)
} 
}

注意:ThemeContent是什么并不清楚,但可能需要使其符合其他协议

使用Binding。修改你的ThemeEditor视图

struct ThemeEditor: View {
@Binding private var newTheme: ThemeContent?
@Binding var isValid: Bool
@State private var themeName = ""

init(forTheme theme: Binding<ThemeContent?>, isValid: Binding<Bool>) {
self._newTheme = theme
self._isValid = isValid
}
var body: some View {
....
}
}

对于表格代码

.sheet(isPresented: $showThemeEditor) {
ThemeEditor(forTheme: $themeToEdit, isValid: $isValid)
}

行动

.onTapGesture {
/* themeInfo is of type struct ThemeContent: Codable, Hashable, Identifiable */
self.themeToEdit = game.themeInfo
self.showThemeEditor = true

}

最新更新