Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
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

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.

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
Banner background image