The code from https://github.com/onmyway133/blog/issues/594, and make some changes.
It's very simple, create a SwiftUI + Appkit
project, copy and paste the code below to the project.
import SwiftUI
struct SelectFileView: View {
let buttonTitle: String
@State var isDrop: Bool = false
var body: some View {
VStack(alignment: .leading) {
Button(action: {}) {
Text(buttonTitle)
}
.offset(x: -16)
Text("Alternatively, you can drag and drop file here")
.font(.footnote)
.foregroundColor(Color.gray)
}
.border(isDrop ? Color.orange : Color.clear)
.onDrop(of: ["public.image"], delegate: self)
.padding(32)
}
}
extension SelectFileView: DropDelegate {
func dropEntered(info: DropInfo) {
print("dropEntered")
self.isDrop = true
}
func dropExited(info: DropInfo) {
print("dropExited")
self.isDrop = false
}
func performDrop(info: DropInfo) -> Bool {
guard
let itemProvider = info.itemProviders(for: ["public.image"]).first
else { return false }
itemProvider.loadItem(forTypeIdentifier: "public.image", options: nil) { item, error in
guard
let data = item as? Data,
let url = URL(dataRepresentation: data, relativeTo: nil)
else { return }
}
return true
}
}
struct ContentView: View {
var body: some View {
SelectFileView(buttonTitle: "Drop Test")
}
}
After building and running on Xcode 12.0 beta 2 (12A6163b)
, it always print dropExited
, and this is the problem.
dropEntered(info:)
not trigged, but dropExited(info:)
works