๐ฐ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
}
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