Limit SwiftUI modifier .onMove() to current list only

Viewed 742

I have declared two separated lists of items within a List/ForEach as the following:

List {
    ForEach(model) { item in
        ItemView(item)
            .tag(item.id)
    }
    .onMove(perform: { rows, newIndex in
        model.move(items: rows, destination: newIndex)
    })
}

Both lists use a different model, identified by its IDs. Nevertheless, on macOS, I have realized that I can drag items from one list to the other list, despite their different IDs.

Is there any possibility to disable the drop functionality (e.g. via .onInsert()) of the other list while dragging? I have already a functionality implemented using NSItemProviderReading and NSItemProviderWriting to be able to detect when the user has started dragging.

1 Answers

You could try to ignore the inserts, like in this test code that works for me:

struct ContentView: View {
    @State private var model1 = ["One", "Two", "Three", "Four"]
    @State private var model2 = ["Five", "Six", "Seven", "Eight"]
    
    var body: some View {
        VStack {
            List {
                ForEach(model1, id: \.self) { item in
                    Text(item)
                }
                .onMove { (indexSet, index) in
                    model1.move(fromOffsets: indexSet, toOffset: index)
                }
                .onInsert(of: [UTType.text]) { pos,prov in
                    print("\n-----> ignoring insert in model1")
                }
            }
            Divider()
            List {
                ForEach(model2, id: \.self) { item in
                    Text(item)
                }
                .onMove { (indexSet, index) in
                    model2.move(fromOffsets: indexSet, toOffset: index)
                }
                .onInsert(of: [UTType.text]) { pos,prov in
                    print("\n-----> ignoring insert in model2")
                }
            }
        }
    }
}
Related