Reordering Rows in SwiftUI ListView: A Step-by-Step Guide
In this post, I want to talk about moving the rows in a ListView.
we’ll create an app that implements a List
view that allows users to move and reorganize rows.
Setup the List
Add a @State
variable to the ContentView
struct that holds an array of countries:
@State private var countries = ["USA", "Canada", "Mexico", "England", "Spain", "Germany", "Cameroon", "South Africa" , "Japan", "South Korea"]
Replace the body variable’s text view with a NavigationStack
, a List
, and modifiers for navigating.
var body: some View {
NavigationStack {
List {
ForEach(countries, id: \.self) {
country in
Text(country)
}
}
.navigationTitle("Countries")
.navigationBarTitleDisplayMode(.inline)
}
}
Add Move feature to rows
To move list rows, you need to wrap the list in a NavigationStack
, add the .onMove(perform:)
modifier to the ForEach
struct, and add a .toolbar
modifier with an EditButton
to the list.
NavigationStack {
List {
ForEach(countries, id: \.self) {
country in
Text(country)
}
.onMove(perform: moveRow)
}
.navigationTitle("Countries")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
EditButton()
}
}
Now, let’s add the function that gets called when we try to move a row.
The moveRow(source: IndexSet, destination: Int)
function takes two parameters, source
and destination
, which represent the current index of the item to be moved and its destination index, respectively.
private func moveRow(source: IndexSet, destination: Int) {
countries.move(fromOffsets: source, toOffset: destination)
}
Let’s run our application. and click and drag on the hamburger menu symbol at the right of each country to move it to a new location:
Conclusion
Implementing row reordering in a SwiftUI ListView can greatly enhance the user experience of your app. By following the steps outlined in this post, you’ve empowered users to effortlessly rearrange items according to their preferences. This feature adds a layer of interactivity and customization, making your app more engaging and user-friendly. Experiment with this functionality to further refine your app and provide a seamless experience for your users.
To access the code discussed in this post, visit here.