How to add drag and drop in SwiftUI

Issue #594

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
struct SelectFileView: View {
let buttonTitle: String
@State var isDrop: Bool = false

var body: some View {
VStack(alignment: .leading) {
Button(action: {}) {
Text(buttonTitle)
}
.buttonStyle(ActionButtonStyle())
.offset(x: -16)
Text("Alternatively, you can drag and drop file here")
.font(.footnote)
.foregroundColor(Color.gray)
}
.border(isDrop ? R.color.separator : Color.clear)
.onDrop(of: [Constants.urlFileType], delegate: self)
.padding(.bottom, 32)
}
}

extension SelectFileView: DropDelegate {
func dropEntered(info: DropInfo) {
self.isDrop = true
}

func dropExited(info: DropInfo) {
self.isDrop = false
}

func performDrop(info: DropInfo) -> Bool {
guard
let itemProvider = info.itemProviders(for: [Constants.urlFileType]).first
else { return false }

itemProvider.loadItem(forTypeIdentifier: Constants.urlFileType, options: nil) { item, error in
guard
let data = item as? Data,
let url = URL(dataRepresentation: data, relativeTo: nil)
else { return }

}

return true
}
}

Updated at 2020-07-09 01:45:55

Comments