Advertisement
Guest User

Untitled

a guest
Jun 8th, 2022
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.91 KB | None | 0 0
  1. import SwiftUI
  2. import UniformTypeIdentifiers
  3.  
  4. struct ContentView: View {
  5.     @State var items = ["1", "2", "3"]
  6.     @State var draggedItem : String?
  7.     @State var isHovering: Bool = false
  8.  
  9.     var body: some View {
  10.         VStack {
  11.             ForEach(items, id:\.self) { item in
  12.                 HStack {
  13.                     Image(systemName: "line.horizontal.3")
  14.                     Text(item)
  15.                 }
  16.                 .frame(minWidth: 0, maxWidth: .infinity, minHeight: 50)
  17.                 .border(Color.black).background(Color.teal)
  18.                 .onDrag({
  19.                     self.draggedItem = item
  20.                     return NSItemProvider(item: nil, typeIdentifier: item)
  21.                 })
  22.                 .onDrop(of: [UTType.text], delegate: MyDropDelegate(item: item, items: $items, draggedItem: $draggedItem))
  23.             }
  24.             .onMove { indices, newOffset in
  25.                 self.items.move(
  26.                     fromOffsets: indices,
  27.                     toOffset: newOffset
  28.                 )
  29.             }
  30.         }
  31.     }
  32. }
  33.  
  34. struct MyDropDelegate : DropDelegate {
  35.     let item : String
  36.     @Binding var items : [String]
  37.     @Binding var draggedItem : String?
  38.  
  39.     func validateDrop(info: DropInfo) -> Bool {
  40.         return true
  41.     }
  42.    
  43.     func dropUpdated(info: DropInfo) -> DropProposal? {
  44.         return DropProposal(operation: .move)
  45.     }
  46.    
  47.     func performDrop(info: DropInfo) -> Bool {
  48.         return true
  49.     }
  50.  
  51.     func dropEntered(info: DropInfo) {
  52.         guard let draggedItem = self.draggedItem else {
  53.             return
  54.         }
  55.  
  56.         if draggedItem != item {
  57.             let from = items.firstIndex(of: draggedItem)!
  58.             let to = items.firstIndex(of: item)!
  59.             withAnimation(.default) {
  60.                 self.items.move(fromOffsets: IndexSet(integer: from), toOffset: to > from ? to + 1 : to)
  61.             }
  62.         }
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement