'SwiftUI disable drag function

I have a simple view which contains a group of Buttons which allow drag feature depends on condition. How can i disable .onDrag based on the condition? The .disabled only disable click function.

    ScrollView
    {
        ForEach(animals, id: \.id)
        {
            animal in
            Button(action:{})
            {
               Text(animal.name)
            }
                .disabled(!animal.isEnable)
                .onDrag
                {
                    let provider = NSItemProvider(object: animal.name as NSString )
                    provider.suggestedName = animal.name
                    return provider
                }
          }
    }


Solution 1:[1]

Here is a solution with helper modifier. Tested with Xcode 11.4.

// @available(iOS 13.4, *) - needed for iOS
struct Draggable: ViewModifier {
    let condition: Bool
    let data: () -> NSItemProvider

    @ViewBuilder
    func body(content: Content) -> some View {
        if condition {
            content.onDrag(data)
        } else {
            content
        }
    }
}

// @available(iOS 13.4, *) - needed for iOS
extension View {
    public func drag(if condition: Bool, data: @escaping () -> NSItemProvider) -> some View {
        self.modifier(Draggable(condition: condition, data: data))
    }
}

and updated your code would be

ForEach(animals, id: \.id)
{
    animal in
    Button(action:{})
    {
        Text(animal.name)
    }
    .disabled(!animal.isEnable)
    .drag(if: animal.isEnable) {     // << here !!
        let provider = NSItemProvider(object: animal.name as NSString )
        provider.suggestedName = animal.name
        return provider
    }
}

backup

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1