Book Image

SwiftUI Cookbook - Second Edition

By : Giordano Scalzo, Edgar Nzokwe
Book Image

SwiftUI Cookbook - Second Edition

By: Giordano Scalzo, Edgar Nzokwe

Overview of this book

SwiftUI provides an innovative and simple way to build beautiful user interfaces (UIs) for all Apple platforms, from iOS and macOS through to watchOS and tvOS, using the Swift programming language. In this recipe-based cookbook, you’ll cover the foundations of SwiftUI as well as the new SwiftUI 3 features introduced in iOS 15 and explore a range of essential techniques and concepts that will help you through the development process. The cookbook begins by explaining how to use basic SwiftUI components. Once you’ve learned the core concepts of UI development, such as Views, Controls, Lists, and ScrollViews, using practical implementations in Swift, you'll advance to adding useful features to SwiftUI using drawings, built-in shapes, animations, and transitions. You’ll understand how to integrate SwiftUI with exciting new components in the Apple development ecosystem, such as Combine for managing events and Core Data for managing app data. Finally, you’ll write iOS, macOS, and watchOS apps by sharing the same SwiftUI codebase. By the end of this SwiftUI book, you'll have discovered a range of simple, direct solutions to common problems encountered when building SwiftUI apps.
Table of Contents (17 chapters)

Adding rows to a list

The most common actions users might want to be able to perform on a list include adding, editing, or deleting items.

In this recipe, we'll go over the process of implementing those actions on a SwiftUI list.

Getting ready

Create a new SwiftUI project and call it ListRowAdd.

How to do it…

Let's create a list with a button at the top that can be used to add new rows to the list. The steps are as follows:

  1. Create a state variable in the ContentView struct that holds an array of numbers:
     @State var numbers = [1,2,3,4]
  2. Add a NavigationView struct and a List view to the ContentView struct's body:
            NavigationView{
                List{
                    ForEach(self.numbers, id:\.self){
                        number in
                        Text("\(number)")
                    }
                }
            }
  3. Add a .navigationBarTitle modifier to the list with a title:
    .navigationBarTitle("Number List", displayMode:
      .inline)
  4. Add a navigationBarItems modifier to the list with a function to trigger an element being added to the row:
       .navigationBarItems(trailing: Button("Add", action:
         addItemToRow))
  5. Implement the addItemToRow function and place it immediately after the body view's closing brace:
        private func addItemToRow() {
            self.numbers.append(Int.random(in: 5 ..< 100))
        }

    The preview should look as follows:

Figure 2.5 – ListRowAdd preview

Figure 2.5 – ListRowAdd preview

You can now run the preview and click the Add button to add new items to the list.

How it works…

Our state variable, numbers, holds an array of numbers. We made it a state variable so that the view that's created by our ForEach struct gets updated each time a new number is added to the array.

The .navigationBarTitle ("Number List," displayMode: .inline) modifier adds a title to the top of the list and within the standard bounds of the navigation bar. The display mode is optional, so you could remove it to display the title more prominently. Other display modes include automatic, to inherit from the previous navigation item, and large, to display the title within an expanded navigation bar.

The .navigationbartItems(…) modifier adds a button to the trailing end of the navigation section. The button calls the addItemToRow function when clicked.

Finally, the addItemToRow function generates a random number between 0-99 and appends it to the numbers array. The view gets automatically updated since the numbers variable is a state variable and a change in its state triggers a view refresh.

Important Note

In our list's ForEach struct, we used \.self as our id parameter. However, we may end up with duplicate numbers in our list as we generate more items. Identifiers should be unique, so using values that could be duplicated may lead to unexpected behaviors. Remember to ONLY use unique identifiers for apps meant to be deployed to users.