Skip to content

Dynamically Adding a Row to a List in SwiftUI

SwiftUI, Lists, Dynamic Views1 min read

In SwiftUI, creating dynamic lists is a common requirement when developing applications. Whether it's adding items to a shopping cart, managing a to-do list, or any other scenario where the user needs to dynamically interact with a list of items, SwiftUI provides a straightforward way to achieve this. In this article, we will explore how to dynamically add a row to a list in SwiftUI, empowering you to create more interactive and engaging user interfaces.

Setting Up the Project

Before diving into the code, let's set up a basic SwiftUI project. Assuming you have Xcode installed, open it and create a new SwiftUI project. Once your project is set up, you can proceed to implement the dynamic row addition functionality.

Dynamically Adding Rows

To dynamically add a row to a list in SwiftUI, we can leverage the power of SwiftUI's @State property wrapper in combination with an array to manage the list's data.

First, create a simple model to represent each item in the list. For instance, if we were building a simple to-do list app, our model could be defined as follows:

1struct TodoItem: Identifiable {
2 let id = UUID()
3 var task: String

Next, within your SwiftUI view, declare a state variable to hold an array of these TodoItem instances:

1@State private var todoItems: [TodoItem] = [
2 TodoItem(task: "Buy groceries"),
3 TodoItem(task: "Finish project")

Now that we have our initial data set up, we can create a form or a list that displays these items using a ForEach loop:

1List {
2 ForEach(todoItems) { item in
3 Text(item.task)
4 }

To allow users to dynamically add a new item to the list, we can include a button which, when tapped, adds a new item to the array:

1Button(action: {
2 let newTask = "New task" // You can replace this with your desired logic to obtain the new task
3 todoItems.append(TodoItem(task: newTask))
4}) {
5 Text("Add Task")