首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尽管使用SWIFT游乐场自己的代码,但我无法在所有视图中更新数组

尽管使用SWIFT游乐场自己的代码,但我无法在所有视图中更新数组
EN

Stack Overflow用户
提问于 2022-08-01 09:03:23
回答 1查看 144关注 0票数 0

我是新来的所以请原谅我。

我正在iPad上学习斯威夫特游乐场教程。他们很好,但有点小马车。

我遵守了教程。我应该用代码来显示5个生物,他们的名字和表情符号。我可以按add键转到另一个视图并将更多内容添加到列表中。如果我将一个ForEach代码放入add视图,我可以看到列表更新。但在其他视图中,它似乎没有更新。当我来回导航的时候,更新就消失了。

本教程让我们使用附加项将项目添加到列表中。使用EnvironmentObject包装器调用列表。我在网上搜索了一下,找不到出什么问题了。

有人能帮忙吗?

谢谢

代码中的代码演练注释似乎是在从应用程序复制时自动添加的。

第一个文件: CreatureZoo

代码语言:javascript
复制
import SwiftUI

//#-learning-task(creatureZoo)

/*#-code-walkthrough(creatureZoo.observableObject)*/
class CreatureZoo : ObservableObject {
    /*#-code-walkthrough(creatureZoo.observableObject)*/
    /*#-code-walkthrough(creatureZoo.creatures)*/
    /*#-code-walkthrough(creatureZoo.published)*/ @Published /*#-code-walkthrough(creatureZoo.published)*/var creatures = [
        /*#-code-walkthrough(creatureZoo.creature)*/
        Creature(name: "Gorilla", emoji: ""),
        /*#-code-walkthrough(creatureZoo.creature)*/
        Creature(name: "Peacock", emoji: ""),
        Creature(name: "Squid", emoji: ""),
        Creature(name: "Owl", emoji: ""),
        Creature(name: "Unicorn", emoji: "")
        //#-learning-task(addCreatures)
        
    ]
    /*#-code-walkthrough(creatureZoo.creatures)*/
}

/*#-code-walkthrough(creatureZoo.creatureStruct)*/
struct Creature : Identifiable {
    var name : String
    var emoji : String
    
    var id = UUID()
    var offset = CGSize.zero
    var rotation : Angle = Angle(degrees: 0)
}
/*#-code-walkthrough(creatureZoo.creatureStruct)*/


// Should be hidden probably
extension CreatureZoo {
    func randomizeOffsets() {
        for index in creatures.indices {
            creatures[index].offset = CGSize(width: CGFloat.random(in: -200...200), height: CGFloat.random(in: -200...200))
            creatures[index].rotation = Angle(degrees: Double.random(in: 0...720))
        }
    }
    
    func synchronizeOffsets() {
        let randomOffset = CGSize(width: CGFloat.random(in: -200...200), height: CGFloat.random(in: -200...200))
        for index in creatures.indices {
            creatures[index].offset = randomOffset
        }
    }
    
    func indexFor(_ creature: Creature) ->  Double {
        if let index = creatures.firstIndex(where: { $0.id == creature.id }) {
            return Double(index)
        }
        return 0.0
    }
}

第二文件CreatureRow

代码语言:javascript
复制
import SwiftUI

struct CreatureRow: View {
    var creature : Creature
    
    var body: some View {
        HStack {
            Text(creature.name)
                .font(.title)
            
            Spacer()
            
            Text(creature.emoji)
                .resizableFont()
                .frame(minWidth: 125)
        }
        
        
    }
}

struct CreatureRow_Previews: PreviewProvider {
    static var previews: some View {
        CreatureRow(creature: Creature(name: "Dodo Bird", emoji: ""))
    }
}

第3文件CreatureEditor

代码语言:javascript
复制
import SwiftUI
import Guide

struct CreatureEditor: View {
    //#-learning-task(defineVariablesCreatureEditor)
    @Environment(\.dismiss) var dismiss
    
    @State var newCreature : Creature = Creature(name: "", emoji: "")
    @EnvironmentObject var data : CreatureZoo
    var body: some View {
        SPCAssessableGroup(view: self) {
            
            
            VStack(alignment: .leading) {
                
                
                Form {
                    Section("Name") {
                        //#-learning-task(addACreatureEditorTextField)
                        TextField("Creature Name", text: $newCreature.name)
                    }   
                    
                    Section("Emoji") {
                        TextField("Emoji", text: $newCreature.emoji)
                        
                    }
                    
                    Section("Creature Preview") {
                        CreatureRow(creature: newCreature)
                    }
                    
                    Section("Current Creatures") {
                        ForEach(data.creatures) { creature in 
                            
                            CreatureRow(creature: creature)
                            /*#-code-walkthrough(forEach.id)*/
                            
                        }
                        
                    }
                }
                
                
            }
            
            
            .toolbar { 
                ToolbarItem { 
                    Button("Add") { 
                        data.creatures.append(newCreature)
                        dismiss()
                        
                        
                    }
                }
            }
            
        }.environmentObject(CreatureZoo()) // I added this myself to try to make things work 
    }
    
}

struct CreatureEditor_Previews: PreviewProvider {
    static var previews: some View {
        NavigationView() {
            CreatureEditor().environmentObject(CreatureZoo())
        }
    }
}

第4文件contentView

代码语言:javascript
复制
import SwiftUI
import Guide

struct ContentView: View {
    
    @EnvironmentObject var data : CreatureZoo
    
    //#-learning-task(cleanUpApp)
    //#-learning-task(createYourOwn)

    var body: some View {
        SPCAssessableGroup(view: self) {
            List {
                
                Text("ContentView")
                
                Section("Dance") {
                    NavigationLink("make the creatures dance") {
                        DancingCreatures()
                            .navigationTitle("Dancing Creatures")
                            .environmentObject(CreatureZoo())
                    }
                    //#-learning-task(addNavLinkCreatureDance)
                    
                }
                /*#-code-walkthrough(forEach.id)*/
                Section("Add new creature") {
                    NavigationLink(" Add new") {
                        
                        CreatureEditor()
                            .navigationTitle("Add new")
                            .environmentObject(CreatureZoo())
                        
                    }
                    
                }
                ForEach(data.creatures) { creature in 
                    
                    CreatureRow(creature: creature)
                    /*#-code-walkthrough(forEach.id)*/
                    
                }
                
                .onDelete { indexSet in 
                    data.creatures.remove(atOffsets: indexSet)
                }
                
                                
            }
            .toolbar { 
                ToolbarItem { 
                    NavigationLink("Add") { 
                        CreatureEditor()
                            .navigationTitle("Add new creature")
                            .environmentObject(CreatureZoo())
                    }
                }
            }
            
        }
    }
}

第5文件myApp

代码语言:javascript
复制
import SwiftUI
import Guide
//#-learning-task(myApp)

@main
/*#-code-walkthrough(myApp.appProtocol)*/
struct MyApp: App {
    /*#-code-walkthrough(myApp.appProtocol)*/
    @StateObject var data = CreatureZoo()
    /*#-code-walkthrough(myApp.body)*/
    var body: some Scene {
        SPCAssessableWindowGroup(app: self, assessmentCandidates: [CreatureZoo()]) {
            NavigationView { 
                
                
                ContentView()
                    .navigationTitle("My Creatures")
                    .environmentObject(data)
                
            }
            
                
            }
            

            /*#-code-walkthrough(myApp.contentView)*/
            
            /*#-code-walkthrough(myApp.contentView)*/

        }
    }
    /*#-code-walkthrough(myApp.body)*/
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-01 09:22:47

当您添加.environmentObject(CreatureZoo())时,您将创建一个在视图之间不共享的新实例。您应该在.environmentObject文件中添加一次App

在ContentView中,这个.environmentObject(CreatureZoo())应该是.environmentObject(data)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73191314

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档