Today I will show you how to adjust the order of elements in the List. (demo with NavigationView).
import SwiftUI
struct ContentView: View {
/// 1. Use an array as the data source for the List.
@State var colors = ["Red", "Green", "Blue"]
var body: some View {
/// 2. Add a NavigationView. The function of NavigationView is similar to that of UINavigationController, which is mostly used to switch between views.
NavigationView {
/// 3. create a List
List {
/// 4. Add a forEach method to iterate over the array.
ForEach(colors, id: \.self) { color in
/// 5. Use Text to show the elements.
Text(color)
}
/** 6.
Add an `onMove` method so that the elements of the List can be moved.
This method has two parameters:
- source: The original position's index.
- destination: The destination position's index.
*/
.onMove { source, destination in
/// 7. When the elements in the List are moved, the elements in the array also need to be moved to keep the interface and data from changing simultaneously.
self.colors.move(fromOffsets: source, toOffset: destination)
}
}
/// 8. Set the title text of the navigation bar
.navigationTitle(Text("Edit"))
.navigationBarTitleDisplayMode(.large)
/// 9. add an edit button
.toolbar { EditButton() }
}
}
}
Follow me on:
Comments