Responding to gestures: Long pressing

Responding to gestures: Long pressing

Discover how to respond to long press gestures in a SwiftUI app to create interactive elements

A gesture where the user holds down touch for an elongated period of time on a view is called a long gesture. In SwiftUI, you can set it up using the LongPressGesture structure. It is quite useful for starting a continuous action or highlighting items, for example.

 LongPressGesture(minimumDuration: 1, maximumDistance: 10)

It can be set as a gesture on any view. You define the minimum duration time for activation through the minimumDuration parameter.

The maximumDistance parameter defines how much the user’s finger can move before cancelling the gesture. If the finger moves more than a certain number of points, the gesture is canceled.

struct LongPressView: View {
    
    @State var isPressed = false
    
    var body: some View {
    
        Circle()
            .fill(isPressed ? .green : .blue)
            .frame(width: 100, height: 100)
            .overlay(
                Image(systemName: isPressed ? "checkmark" : "hand.tap")
                    .foregroundColor(.white)
                    .font(.system(size: 30))
            )
            .gesture(
                 LongPressGesture(minimumDuration: 1, maximumDistance: 10)
                    .onEnded { _ in
                        isPressed = true
                    }
            )
    }
}
0:00
/0:10

You can also set up a long gesture on a view by using the modifier onLongPressGesture(minimumduration:maximumdistance:perform:onpressingchanged:).

.onLongPressGesture(
    minimumDuration: 1,
    maximumDistance: 50,
    perform: {
        completeLongPress = true
    },
    onPressingChanged: { pressing in
        isPressing = pressing
    }
)

Here is an example of an interaction with a view using the long gesture modifier.

struct OnLongPressView: View {
 
    @State var isPressing = false
    @State var completeLongPress = false
    
    var body: some View {
        Circle()
            .fill(completeLongPress ? .green : (isPressing ? .orange : .blue))
            .frame(width: 100, height: 100)
            
            .onLongPressGesture(
                minimumDuration: 1,
                maximumDistance: 50,
                perform: {
                    completeLongPress = true
                },
                onPressingChanged: { pressing in
                    isPressing = pressing
                }
            )
    }
}
0:00
/0:06

Check the following articles of the Apple Developer documentation to explore other aspects of defining gestures in SwiftUI: