Adding Items
Part of the Introduction to SwiftUI section of Coddy's Swift journey. Lesson 32 of 50.
Keep the items in @State and the list updates whenever the array changes. A text field and a button are enough to add items:
@State private var items = ["Milk"]
@State private var newItem = ""
var body: some View {
VStack {
TextField("New item", text: $newItem)
Button("Add") {
items.append(newItem)
newItem = ""
}
List(items, id: \.self) { item in
Text(item)
}
}
}items.append(newItem) adds the typed text to the array, and newItem = "" clears the field for the next item. Because items is state, the list shows the new row right away.
A button can be disabled while the field is empty: .disabled(newItem.isEmpty).
Challenge
MediumMake the Add button work: append newItem to items and then clear the field. The list already shows items.
Try it yourself
import SwiftUI
@main
struct CoddyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction to SwiftUI
Practice on your own: Swift playground