Michał Ziobro
Michał Ziobro

Reputation: 11822

How to define drag gesture in property on SwiftUI view

I cannot return DragGesture from computed property like below

'_EndedGesture<_ChangedGesture<DragGesture>>' to return type 'DragGesture'


 var dimDrag : DragGesture {
        DragGesture()
            .onChanged({
                    print("Dim drag")

                    if $0.translation.width > 0 {
                        self.model.menuOffset = max(min($0.translation.width, UIScreen.main.bounds.width*0.7), 0.0)
                    } else {
                        self.model.menuOffset = max(min(UIScreen.main.bounds.width*0.7 + $0.translation.width, UIScreen.main.bounds.width*0.7), 0.0)
                    }

            })
            .onEnded({
                    if $0.translation.width < -100 {
                        withAnimation {
                            self.model.isMenuOpen = true
                            self.model.menuOffset = 0.0
                        }
                    } else if $0.translation.width > 100 {
                        withAnimation {
                            self.model.isMenuOpen = false
                            self.model.menuOffset = UIScreen.main.bounds.width*0.7
                        }
                    }
            })
    }

Upvotes: 4

Views: 766

Answers (2)

Partha G
Partha G

Reputation: 1246

As it is returning _EndedGesture<_ChangedGesture<DragGesture>> and not DragGesture, one can declare the computed property like this :

 var dimDrag: some Gesture {
        DragGesture()
            .onChanged({
                    if $0.translation.width > 0 {
                        self.model.menuOffset = max(min($0.translation.width, UIScreen.main.bounds.width*0.7), 0.0)
                    } else {
                        self.model.menuOffset = max(min(UIScreen.main.bounds.width*0.7 + $0.translation.width, UIScreen.main.bounds.width*0.7), 0.0)
                    }
            })
            .onEnded({
                    if $0.translation.width < -100 {
                        withAnimation {
                            self.model.isMenuOpen = true
                            self.model.menuOffset = 0.0
                        }
                    } else if $0.translation.width > 100 {
                        withAnimation {
                            self.model.isMenuOpen = false
                            self.model.menuOffset = UIScreen.main.bounds.width*0.7
                        }
                    }
            })
    }

One can make this variable as part of private extension.

Upvotes: 4

Asperi
Asperi

Reputation: 258541

The following works for me:

let myDrag = {
    DragGesture()
        .onChanged({ value in

        })
        .onEnded { value in

        }
    }()

Upvotes: 0

Related Questions