๐Ÿ”ฐadd item to list

SwiftUI โŸฉ view โŸฉ state โŸฉ actions โŸฉ add item to list

๐Ÿ“ ContentView

List {
    // assume `data` is an environment object
    ForEach(data.creatures) { creature in 
        CreatureRow(creature: creature)
    }
}
// โญ๏ธ add toolbar item "New" to navigation bar
.toolbar { 
    ToolbarItem { 
        NavigationLink("New") { 
            // new data item editor view
            CreatureEditor()
                .navigationTitle("+ Creature")
        }
    }
}

๐Ÿ“ CreatureEditor

// โญ๏ธ new data item editor view
struct CreatureEditor: View {
    
    // โญ๏ธ get environment object
    @EnvironmentObject var data: CreatureZoo
    
    // โญ๏ธ new data item (a state value)
    @State private var creature = Creature(name: "untitled", emoji: "โ“")
    
    // โญ๏ธโญ๏ธโญ๏ธ ๅ•Ÿ็”จ้—œ้–‰ๆญค view ็š„ๅŠŸ่ƒฝ๏ผˆไบ‹ๅพŒ็”จ dismiss() ้—œ้–‰๏ผ‰
    @Environment(\.dismiss) private var dismiss
    
    var body: some View {
        VStack(alignment: .leading) {
            // โญ๏ธ UI to update data item
            Form {
                Section("Name") {
                    TextField("name", text: $creature.name)
                }   
                Section("Emoji") {
                    TextField("emoji", text: $creature.emoji)
                }
                Section("Creature Preview") {
                    CreatureRow(creature: creature)
                }
            }
        }// VStack
        // โญ๏ธ add toolbar item "Add" to navigation bar
        .toolbar { 
            ToolbarItem { 
                Button("Add") { 
                    // when button is tapped:
                    data.creatures.append(creature)  // โญ๏ธ add item to data
                    dismiss()                        // โญ๏ธ dismiss this view
                }
            }
        }
        
    }// body
}

Last updated