SwiftUI macOS drag & drop file-rul

Updated
Apr 4, 2021 11:40 AM
Created
Apr 4, 2021 11:40 AM
Tags
MemoSwiftSwiftUI.framework
Keywords

struct ContentView: View {

  @State private var droppedImage: Image?

  var body: some View {
    
    HStack {
      ZStack {
        RoundedRectangle(cornerRadius: 16)
          .foregroundColor(.gray)
        Text("Drop Image here")
          .padding()
      }
      .padding(16)
      .onDrop(of: [.fileURL], delegate: ImageDropDelegate(loadedImage: $droppedImage))

      droppedImage?
        .resizable()
        .frame(width: 200, height: 200, alignment: .center)
    }

  }
}

struct ImageDropDelegate: DropDelegate {

  @Binding var loadedImage: Image?

  func performDrop(info: DropInfo) -> Bool {

    print(info)

    guard let first = info.itemProviders(for: [.fileURL]).first else {
      return false
    }

    _ = first.loadObject(ofClass: URL.self) { (url, error) in
      print(url, error)
      if let url = url, let nsImage = NSImage(contentsOf: url) {
        let image = Image(nsImage: nsImage)
        loadedImage = image
      }

    }

    return true
  }
}