Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
SwiftUI Cookbook

You're reading from   SwiftUI Cookbook Discover solutions and best practices to tackle the most common problems while building SwiftUI apps

Arrow left icon
Product type Paperback
Published in Oct 2020
Publisher Packt
ISBN-13 9781838981860
Length 614 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Edgar Nzokwe Edgar Nzokwe
Author Profile Icon Edgar Nzokwe
Edgar Nzokwe
Giordano Scalzo Giordano Scalzo
Author Profile Icon Giordano Scalzo
Giordano Scalzo
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. Chapter 1: Using the Basic SwiftUI Views and Controls 2. Chapter 2: Going Beyond the Single Component with Lists and Scroll Views FREE CHAPTER 3. Chapter 3: Viewing while Building with SwiftUI Preview 4. Chapter 4: Creating New Components and Grouping Views in Container Views 5. Chapter 5: Presenting Extra Information to the User 6. Chapter 6: Drawing with SwiftUI 7. Chapter 7: Animating with SwiftUI 8. Chapter 8: Driving SwiftUI with Data 9. Chapter 9: Driving SwiftUI with Combine 10. Chapter 10: Handling Authentication and Firebase with SwiftUI 11. Chapter 11: Handling Core Data in SwiftUI 12. Chapter 12: Cross-Platform SwiftUI 13. Chapter 13: SwiftUI Tips and Tricks 14. Other Books You May Enjoy

Adding rows to a list

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.

Getting ready

Let's start by creating a new SwiftUI app called AddRowsToList.

How to do it…

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:

  1. Create a state variable in the ContentView struct that holds an array of integers:
    @State var numbers = [1,2,3,4]
  2. Add a NavigationView component containing a List view to the ContentView body:
    NavigationView{
                List{
                    ForEach(self.numbers, id:\.self){                  number in
                        Text("\(number)")
                    }
                }
    }
  3. Add a navigationBarItems modifier to the list closing brace that contains a button that triggers the addItemToRow() function:
    .navigationBarItems(trailing: Button(action: {
                        self.addItemToRow()
                    }){
                        Text("Add")
                    })
  4. Implement the 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))
        }
  5. For the beauty and aesthetics, add a 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)
  6. The resulting code should be as follows:
    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

Figure 2.5 – AddRowToList preview

Run the app live preview and admire the work of your own hands!

How it works…

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.

You have been reading a chapter from
SwiftUI Cookbook
Published in: Oct 2020
Publisher: Packt
ISBN-13: 9781838981860
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime