Reputation: 3548
Using react native PanResponder, how can I block the movement when the screen touch coordinates are outside of a certain range of values?
For example, how can I prevent users from moving a component below a certain y position on the screen?
The PanResponder uses the Gesture Responder System.
I am carefully reading the documentation, but I cannot find the answer.
Any help is greatly appreciated.
Upvotes: 6
Views: 4617
Reputation: 51
The transform and clamp method will work to some extent. However, the component might stuck at the clamp value b/c the user may try to move the component repeatedly so that the accumulated distance is already far beyond limit.
This will looks like it get stuck. One needs to move it to the opposite direction many time to get the accumulated distance back in desired regime.
I described how to solve a similar problem by setting limits in pan.setOffset, which may be helpful to others. See my answer at ReactNative PanResponder limit X position
Upvotes: 0
Reputation: 31
I solved it using interpolate
transform: [
{
translateX: this._translateX.interpolate({
inputRange: [0, 100],
outputRange: [0, 100],
extrapolate: 'clamp',
}),
},
],
Upvotes: 2
Reputation: 2022
Looking at the PanResponder documentation page you provided (https://facebook.github.io/react-native/docs/panresponder.html), I think you could modify the example to meet your needs.
The function responsible for taking action in response to a gesture is a property of PanResponder called onPanResponderMove, in the example code from the documentation this looks like:
_handlePanResponderMove: function(e: Object, gestureState: Object) {
this._circleStyles.style.left = this._previousLeft + gestureState.dx;
this._circleStyles.style.top = this._previousTop + gestureState.dy;
this._updateNativeStyles();
},
Where the gestureState object looks like this:
stateID - ID of the gestureState- persisted as long as there at least one touch on screen
moveX - the latest screen coordinates of the recently-moved touch
moveY - the latest screen coordinates of the recently-moved touch
x0 - the screen coordinates of the responder grant
y0 - the screen coordinates of the responder grant
dx - accumulated distance of the gesture since the touch started
dy - accumulated distance of the gesture since the touch started
vx - current velocity of the gesture
vy - current velocity of the gesture
numberActiveTouches - Number of touches currently on screen
You might add a conditional check in _handlePanResponderMove to determine if the gestureState.y0 is below some threshold, and only apply a change if so
Upvotes: 8