SwiftUI OnDrop function depending on condition

Viewed 1004

We are using the OnDrop() function in SwiftUI for a MacOS application. It works really great. However, I want to allow the onDrop function only on a special condition. I tried executing the code after the onDrag only if that condition is true, which works fine. However, there is still the dragging animation / mouse drag effect visible which shouldn’t be visible.

That is the code we are using:

.onDrop(of: [“public.file-url”], isTargeted: $userData.shopPopOver) { providers -> Bool in
for provider in providers
{

Can I only add that .onDrop on a condition. Just to show an example, which surely is not working:

if (condition)
{
.onDrop(of: [“public.file-url”], isTargeted: $userData.shopPopOver) { providers -> Bool in

Thanks in advance!

1 Answers

Here is custom modifier that can be used for described use-case

struct Droppable: ViewModifier {
    let condition: Bool
    let types: [String]
    let tracking: Binding<Bool>?
    let action: ([NSItemProvider]) -> Bool

    @ViewBuilder
    func body(content: Content) -> some View {
        if condition {
            content.onDrop(of: types, isTargeted: tracking, perform: action)
        } else {
            content
        }
    }
}

extension View {
    public func acceptDrop(if condition: Bool, of supportedTypes: [String], isTargeted: Binding<Bool>?, perform action: @escaping ([NSItemProvider]) -> Bool) -> some View {
        self.modifier(Droppable(condition: condition, types: supportedTypes, tracking: isTargeted, action: action))
    }
}

Related