This is my simple app. Where I’m using .onMove method to change the order of my item. But now I can only change the order, but it doesn’t save it(leave on a new position). So when I stopped holding my item, it immediately returned to its position. How do you think I could fix it?
import SwiftUI
struct HomeView: View {
struct Item: Identifiable {
var id = UUID()
var name: String
var color: Color
}
@State var items = [
Item(name: "Item 1", color: .red),
Item(name: "Item 2", color: .green),
Item(name: "Item 3", color: .blue),
Item(name: "Item 4", color: .brown)
]
var body: some View {
List {
ForEach(items, id: \.id) { item in
Text(item.name)
.frame(maxWidth: .infinity)
.padding()
.background(item.color)
.foregroundColor(.white)
}
.onMove(perform: move)
}
}
func move(from source: IndexSet, to destination: Int) {
items.move(fromOffsets: source, toOffset: destination)
}
}
struct HomeView_Previews: PreviewProvider {
static var previews: some View {
HomeView()
}
}
>Solution :
When you test on simulator or device it works. This is weird behaviour of SwiftUI preview. No idea why it doesn’t work correctly there.
On preview it would work only if you enable EditMode.
For recommendation, you can handle the move by List itself:
var body: some View {
List($items, editActions: .move) { $item in
Text(item.name)
.frame(maxWidth: .infinity)
.padding()
.background(item.color)
.foregroundColor(.white)
}
}
Everything works out of box 😉
And you can report this problem also via Feedback Assistant