Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
                }
          }
    }
like image 490
user1151874 Avatar asked Jun 14 '26 05:06

user1151874


2 Answers

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
    }
}
like image 63
Asperi Avatar answered Jun 17 '26 01:06

Asperi


Disabled usually won't work.

Create an extension for a View and put if

extension View {
    @ViewBuilder func `if`<Content: View>(_ condition: @autoclosure () -> Bool, transform: (Self) -> Content) -> some View {
        if condition() {
            transform(self)
        } else {
            self
        }
    }
}

and use like this:

Button(//) {
//
}
.if(animal.isEnable, transform: { view in
    view
       .draggable()
       // or .onDrag...
}
like image 34
miff Avatar answered Jun 17 '26 02:06

miff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!