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)

Moving rows in a list

In this section, we will create an app that implements a list view and allows the user to move/reorganize rows.

Getting ready

Let's start by creating a new SwiftUI app in Xcode called MovingListRows.

How to do it…

To allow users to move rows, we need to add a .onMove(..) modifier to the end of the list view's ForEach loop. We also need to embed the list in a navigation view and add a navigationBarItems modifier that implements an EditButton component. The steps are as follows:

  1. Open ContentView.swift. Within the ContentView struct, add a @State variable in Content called countries that contains an array of countries:
    @State var countries = ["USA", "Canada",   "England","Cameroon", "South Africa", "Mexico" ,    "Japan", "South Korea"]
  2. Replace the Text view in the body with a navigation view:
    NavigationView{
            }
  3. Add a list and a ForEach loop within NavigationView that displays the content of the countries variable:
    List {
         	ForEach(countries, id: \.self) { country in
       		Text(country)
           	}.onMove(perform: moveRow)
          }
  4. Add a .onMove(…) modifier to the ForEach loop that calls the moveRow function:
    	ForEach(countries, id: \.self) { country in
       		Text(country)
           	}.onMove(perform: moveRow)
  5. Add the .navigationBarTitle("Countries", displayMode: .inline) and .navigationBarItems(trailing: EditButton()) modifiers to the end of the List view:
    List {
                    .
    			.
    			.
          }
          .navigationBarTitle("Countries",          isplayMode: .inline)
          .navigationBarItems(trailing: EditButton())
  6. Implement the moveRow function at the end of the body variable's closing brace:
    private func moveRow(source: IndexSet, destination: Int){
            countries.move(fromOffsets: source, toOffset:           destination)
        }
  7. The completed ContentView struct should be as follows:
    struct ContentView: View {
        @State var countries = ["USA", "Canada",      "England","Cameroon", "South Africa", "Mexico" ,         "Japan", "South Korea"]
        var body: some View {
            NavigationView{
                List {
                    ForEach(countries, id: \.self) {                   country in
                        Text(country)
                    }
                    .onMove(perform: moveRow)
                }
                .navigationBarTitle("Countries",                displayMode: .inline)
                .navigationBarItems(trailing: EditButton())
            }
        }
        private func moveRow(source: IndexSet,       destination: Int){
            countries.move(fromOffsets: source,           toOffset: destination)
        }
    }

    Run the application in the canvas, on a simulator, or on a physical device. A click on the Edit button at the top-right corner of the screen displays a hamburger symbol to the right of each row. Click and drag the symbol to move the row on which the country is displayed:

Figure 2.8 – MovingListRows preview when running

Figure 2.8 – MovingListRows preview when running

Run the app live preview and move the rows up or down. Nice work!

How it works…

To move list rows, you need to add the list to a navigation view, add the .onMove(perform:) modifier to the ForEach loop, and add a .navigationBarItems(trailing: EditButton()) modifier to the list.

The moveRow(source: IndexSet, destination: Int) function takes two parameters: the source, an IndexSet argument representing the current index of the item to be moved, and the destination, an integer representing the destination of the row. The .onMove(perform:) modifier automatically passes those arguments to the function.