
SwiftUI Cookbook
By :

Lists are usually used to add, edit, remove, or display content from an existing dataset. In this section, we will go over the process of adding items to an already existing list.
Let's start by creating a new SwiftUI app called AddRowsToList
.
To implement the add functionality, we will enclose the List
view in NavigationView
, and add a button to navigationBarItems
that triggers the add function we will create. The steps are as follows:
ContentView
struct that holds an array of integers:@State var numbers = [1,2,3,4]
NavigationView
component containing a List
view to the ContentView
body: NavigationView{ List{ ForEach(self.numbers, id:\.self){ number in Text("\(number)") } } }
navigationBarItems
modifier to the list closing brace that contains a button that triggers the addItemToRow()
function:.navigationBarItems(trailing: Button(action: { self.addItemToRow() }){ Text("Add") })
addItemToRow()
function, which appends a random integer to the numbers array. Place the function within the ContentView
struct, immediately after the body variable's closing brace:private func addItemToRow() { self.numbers.append(Int.random(in: 0 ..< 100)) }
navigationBarTitle
modifier to the end of the list so as to make it display a title at the top of the list:.navigationBarTitle("Number List", displayMode: .inline)
struct ContentView: View { @State var numbers = [1,2,3,4] var body: some View { NavigationView{ List{ ForEach(self.numbers, id:\.self){ number in Text("\(number)") } }.navigationBarTitle("Number List", displayMode: .inline) .navigationBarItems(trailing: Button("Add", action: addItemToRow)) } } private func addItemToRow() { self.numbers.append(Int.random(in: 0 ..< 100)) } }
The resulting preview should be as follows:
Figure 2.5 – AddRowToList preview
Run the app live preview and admire the work of your own hands!
The array of numbers is declared as a @State
variable because we want the view to be refreshed each time the value of the items in the array changes – in this case, each time we add an item to the numbers array.
The .navigationBarTitle("Number List", displayMode: .inline)
modifier adds a title to the list using the .inline display mode
parameter.
The .navigationBarItems(trailing: Button(…)…)
modifier adds a button to the trailing end of the display, which triggers the addItemToRow
function when clicked.
The addItemToRow
function generates a random number in the range 0–99 and appends it to the numbers array.