Book Image

SwiftUI Cookbook

By : Giordano Scalzo, Edgar Nzokwe
Book Image

SwiftUI Cookbook

By: Giordano Scalzo, Edgar Nzokwe

Overview of this book

SwiftUI is an innovative and simple way to build beautiful user interfaces (UIs) for all Apple platforms, right from iOS and macOS through to watchOS and tvOS, using the Swift programming language. In this recipe-based book, you’ll work with SwiftUI and explore a range of essential techniques and concepts that will help you through the development process. The recipes cover the foundations of SwiftUI as well as the new SwiftUI 2.0 features introduced in iOS 14. Other recipes will help you to make some of the new SwiftUI 2.0 components backward-compatible with iOS 13, such as the Map View or the Sign in with Apple View. The cookbook begins by explaining how to use basic SwiftUI components. Then, you’ll learn the core concepts of UI development such as Views, Controls, Lists, and ScrollViews using practical implementation in Swift. By learning drawings, built-in shapes, and adding animations and transitions, you’ll discover how to add useful features to the SwiftUI. When you’re ready, 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 while 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 found in building SwiftUI apps.
Table of Contents (15 chapters)

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.