— SwiftUI, Lists, Dynamic Views — 1 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.
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.
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: String4}
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")4]
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 in3 Text(item.task)4 }5}
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 task3 todoItems.append(TodoItem(task: newTask))4}) {5 Text("Add Task")6}