By default, a SwiftUI TextField
inserts the string value of the file path when a file is dropped on it.
How do you reject items dropped on a SwiftUI TextField
? (Disabling the text field is not an option. One must still be able to paste or type text into it.)
On macOS, you can overlay
the text field with another dropDestination
view, so that whatever is dropped goes to that view.
TextField("Foo", text: $text)
.overlay {
Color.clear
.dropDestination(for: String.self) { _, _ in
false
}
}
By using a transparent view like Color.clear
, you still allow other user interactions on the text field.
Dragging a file over the text field will not even show the "+" sign, because it is not a String
. Dragging some text over it would show the "+" sign, but dropping the text will not do anything. If you want it to change the text, it is trivial to do so.
The same technique also works with the older onDrop
modifier. You can pass an empty array of UTType
s, so nothing can be dropped.
.onDrop(of: [UTType](), isTargeted: nil) { _ in false }