Created
December 28, 2024 11:03
-
-
Save Codelaby/eaa44ea9e83f1a0ea0255849e043fe65 to your computer and use it in GitHub Desktop.
Drag drop two list swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| struct TwoListPlayground: View { | |
| @State private var users1 = ["Paul", "Taylor", "Adele"] | |
| @State private var users2 = ["Pauline", "Tom", "Adam"] | |
| var body: some View { | |
| VStack { | |
| HStack { | |
| Spacer() | |
| Text("Users") | |
| .font(.headline) | |
| Spacer() | |
| EditButton() | |
| Spacer() | |
| .frame(width: 10) | |
| } | |
| HStack(spacing: 0) { | |
| List { | |
| Text("Users 1") | |
| .font(.subheadline) | |
| .onDrop(of: [.plainText], isTargeted: nil, perform: dropOnEmptyList1) | |
| ForEach(users1, id: \.self) { user in | |
| Text(user) | |
| .onDrag { NSItemProvider(object: user as NSString) } | |
| } | |
| .onMove(perform: moveList1) | |
| .onInsert(of: ["public.text"], perform: dropList1) | |
| } | |
| List { | |
| Text("Users 2") | |
| .font(.subheadline) | |
| .onDrop(of: [.plainText], isTargeted: nil, perform: dropOnEmptyList2) | |
| ForEach(users2, id: \.self) { user in | |
| Text(user) | |
| .onDrag { NSItemProvider(object: user as NSString) } | |
| } | |
| .onMove(perform: moveList2) | |
| .onInsert(of: ["public.text"], perform: dropList2) | |
| } | |
| } | |
| .listStyle(.grouped) | |
| } | |
| } | |
| func dropOnEmptyList1(items: [NSItemProvider]) -> Bool { | |
| dropList1(at: users1.endIndex, items) | |
| return true | |
| } | |
| func dropOnEmptyList2(items: [NSItemProvider]) -> Bool { | |
| dropList2(at: users2.endIndex, items) | |
| return true | |
| } | |
| func dropList1(at index: Int, _ items: [NSItemProvider]) { | |
| for item in items { | |
| _ = item.loadObject(ofClass: String.self) { droppedString, _ in | |
| if let ss = droppedString { | |
| DispatchQueue.main.async { | |
| self.users1.insert(ss, at: index) | |
| self.users2.removeAll { $0 == ss } | |
| } | |
| } | |
| } | |
| } | |
| } | |
| func dropList2(at index: Int, _ items: [NSItemProvider]) { | |
| for item in items { | |
| _ = item.loadObject(ofClass: String.self) { droppedString, _ in | |
| if let ss = droppedString { | |
| DispatchQueue.main.async { | |
| self.users2.insert(ss, at: index) | |
| self.users1.removeAll { $0 == ss } | |
| } | |
| } | |
| } | |
| } | |
| } | |
| func moveList1(from source: IndexSet, to destination: Int) { | |
| users1.move(fromOffsets: source, toOffset: destination) | |
| } | |
| func moveList2(from source: IndexSet, to destination: Int) { | |
| users2.move(fromOffsets: source, toOffset: destination) | |
| } | |
| } | |
| #Preview { | |
| TwoListPlayground() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment