Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to save the position of the item when changing the order?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading