Añadir elementos nuevos
Añada filas y mantenga la lista sincronizada.
Añadir elementos nuevos es una lección gratuita de SwiftUI Academy en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de SwiftUI Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de SwiftUI Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Growing the List
A useful list does not stay frozen. Letting users add items is the other half of editing, and it keeps your @State array in charge. ✨
Append to Your Array
Adding a row is just adding data. Call append on your @State array and SwiftUI inserts a fresh row automatically.
items.append(Item(name: "Bread"))A Toolbar Add Button
Most apps add items from a plus button. Put a Button in the toolbar that calls your add logic when tapped.
.toolbar {
Button("Add") { addItem() }
}Use a System Plus Icon
Swap the text for an SF Symbol so it reads as Add. The plus symbol is the universal cue users already understand.
Button {
addItem()
} label: {
Image(systemName: "plus")
}Writing addItem
Your addItem function creates a new model value and appends it. Keep it small and let the array drive the UI.
func addItem() {
items.append(Item(name: "New"))
}Add From a TextField
Often the new item comes from typing. Bind a TextField to a draft string, then append that text when the user confirms.
@State private var draft = ""
TextField("Item", text: $draft)Append Then Clear
After appending, reset the draft so the field is empty for the next entry. Clearing draft keeps the form feeling fresh.
items.append(Item(name: draft))
draft = ""Guard Against Blanks
Do not add empty rows. A quick guard on the trimmed draft stops accidental blank items from cluttering your list.
guard !draft.trimmingCharacters(
in: .whitespaces).isEmpty
else { return }New Rows Animate In
Because the array changed, SwiftUI slides the new row into place. Wrap the append in withAnimation for an even snappier feel.
withAnimation {
items.append(Item(name: draft))
}Insert at the Top
Want newest first? Use insert(at:) with index 0 instead of append, and the row appears at the top of the list.
items.insert(Item(name: draft),
at: 0)One Source of Truth
Add, delete, and move all mutate the same @State array. That single source of truth keeps your whole list consistent.
Quick Check
How do you add a new row to a SwiftUI list?
Recap: Adding Items
You can grow a list by appending to its @State array, often from a toolbar button or a TextField, with guards and animation. 🎉
Aprende Swift con un tutor de IA — gratis
Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.
- Cursos
- 30
- Lecciones
- 120
Preguntas frecuentes
¿La lección «Añadir elementos nuevos» es gratis?
Sí — el texto completo de «Añadir elementos nuevos» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de SwiftUI Academy, actualiza a CoddyKit PRO. El curso de SwiftUI Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Añadir elementos nuevos»?
Añada filas y mantenga la lista sincronizada. Practicas SwiftUI Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar SwiftUI Academy?
No se requiere experiencia previa. SwiftUI Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «Añadir elementos nuevos»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de SwiftUI Academy?
Sí. Cada lección de SwiftUI Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Filas con deslizamiento para eliminar
- Reordenación con onMove
- Añadir elementos nuevos
- Deslizar para actualizar