delete/add item
๐ ๅ่๏ผSwift Playgrounds (Keep Going with Apps) - Sharing Data Between Views.
struct ContentView: View {
// inject data from environment
@EnvironmentObject var data : CreatureZoo
var body: some View {
SPCAssessableGroup(view: self) {
List {
// ...
// injected data
ForEach(data.creatures) { creature in
CreatureRow(creature: creature)
}
// โญ๏ธ action to delete data item ---------------
.onDelete { indexSet in
data.creatures.remove(atOffsets: indexSet)
}
// ---------------------------------------------
}
}
}
}
๐ ContentView
struct ContentView: View {
// inject data from environment
@EnvironmentObject var data : CreatureZoo
var body: some View {
SPCAssessableGroup(view: self) {
List {
// ...
// injected data
ForEach(data.creatures) { creature in
CreatureRow(creature: creature)
}
}
// โญ๏ธ 1. UI to add new data item
.toolbar {
ToolbarItem {
NavigationLink("+") {
// โญ๏ธ 2. new data item editor view
CreatureEditor()
.navigationTitle("+ Creature")
}
}
}
}
}
}
๐ CreatureEditor
// โญ๏ธ new data item editor view
struct CreatureEditor: View {
// โญ๏ธ 1. data to be updated
@EnvironmentObject var data: CreatureZoo
// โญ๏ธ 2. new data item to be added
@State private var creature = Creature(name: "untitled", emoji: "โ")
// โญ๏ธ 3. ็จๆผ้้ๆญค view ็็ฐๅขๅผ
@Environment(\.dismiss) private var dismiss
var body: some View {
SPCAssessableGroup(view: self) {
VStack(alignment: .leading) {
// โญ๏ธ 4. 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)
}
}
}
// โญ๏ธ 5. UI to add new data item
.toolbar {
ToolbarItem {
Button("Add") {
// โญ๏ธ 6. action to add data item
data.creatures.append(creature)
// โญ๏ธ 7. dismiss this view
dismiss()
}
}
}
}
}
}
//
SwiftUI โฉ
State and Data Flow โฉ
App Structure and Behavior โฉ
DismissAction (struct) - defines a
callAsFunction()
method
SwiftOnTap โฉ
DynamicViewContent โฉ onDelete(perform:) -> some DynamicViewContent
View โฉ toolbar(content:)
Last updated