Created
November 26, 2019 03:14
-
-
Save mperezguendulain/cf694db9cd4af0cbfaf29479e1603537 to your computer and use it in GitHub Desktop.
Example of how o move a view with 2 fingers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import { Animated, StyleSheet, View, Text, Dimensions } from 'react-native'; | |
import { | |
PanGestureHandler, | |
State, | |
} from 'react-native-gesture-handler'; | |
export default class DraggableBox extends Component { | |
constructor(props) { | |
super(props); | |
this.animatedViewRef = React.createRef(); | |
this._translateX = new Animated.Value(0); | |
this._lastOffset = { x: 0 }; | |
this.screenWidth = Dimensions.get('window').width; | |
this._onGestureEvent = event => { | |
const relativeOffsetX = event.nativeEvent.translationX; | |
const position = relativeOffsetX + this._lastOffset.x; | |
if (position > 0) { | |
this._translateX.setOffset(0); | |
this._translateX.setValue(0); | |
this._lastOffset.x = 0; | |
} else if (position - this.screenWidth < -1000) { | |
this._translateX.setOffset(-520); | |
this._translateX.setValue(0); | |
this._lastOffset.x = -520; | |
} else { | |
this._translateX.setValue(relativeOffsetX); | |
} | |
}; | |
} | |
_onHandlerStateChange = event => { | |
if (event.nativeEvent.oldState === State.ACTIVE) { | |
const currPosition = event.nativeEvent.translationX + this._lastOffset.x; | |
if (currPosition < 0 && currPosition > -520) { | |
this._lastOffset.x += event.nativeEvent.translationX; | |
} else { | |
this._lastOffset.x += 0; | |
} | |
this._translateX.setOffset(this._lastOffset.x); | |
this._translateX.setValue(0); | |
} | |
}; | |
render() { | |
return ( | |
<View style={styles.container}> | |
<PanGestureHandler | |
{...this.props} | |
minPointers={2} | |
maxPointers={2} | |
onGestureEvent={this._onGestureEvent} | |
onHandlerStateChange={this._onHandlerStateChange}> | |
<Animated.View | |
ref={this.animatedViewRef} | |
style={[ | |
styles.box, | |
{ | |
transform: [ | |
{ translateX: this._translateX }, | |
], | |
}, | |
this.props.boxStyle, | |
]} | |
> | |
<Text>Hola</Text> | |
<Text>Que</Text> | |
<Text>Tal</Text> | |
</Animated.View> | |
</PanGestureHandler> | |
</View> | |
); | |
} | |
} | |
const styles = StyleSheet.create({ | |
container: { | |
flex: 1, | |
justifyContent: 'center', | |
backgroundColor: '#333', | |
}, | |
box: { | |
width: 1000, | |
height: 150, | |
flexDirection: 'row', | |
alignItems: 'center', | |
justifyContent: 'space-between', | |
backgroundColor: '#badc58', | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment