Home > database >  How to implement long press gesture on items within a list using SwiftUI?
How to implement long press gesture on items within a list using SwiftUI?

Time:09-16

I am trying to implement a long press gesture on each item within a list using SwiftUI. The final goal is similar to the email app on iPhone - you can swipe up and down to browse, you can swipe left and delete an item, and you can long press an email and do something else.

With SwiftUI, after implementing the long press gesture for each item, I can't swipe the list at all. It seems like the long press gesture on each item is canceling the swipe actions

enter image description here

CodePudding user response:

I'm updating the solution here as it has some significant delays (more than what you would expect from a long press gesture) when long-pressed. So to mitigate this, you can use onLongPressGesture(minimumDuration:) to set a duration you are comfortable with.

See the example below

List {
    ForEach(0..<100) { x in
        Text("List number -\(x)")
            .onTapGesture {}.onLongPressGesture(minimumDuration: 0.2) { // Setting the minimumDuration to ~0.2 reduces the delay
                print("long press \(x)")
            }
    }
}

NOTE: It is important to have both .onTapGesture {}.onLongPressGesture{} one after the other. The above will not work otherwise.

  • Related