[英]detect when another view is touched - dragging with PanResponder in react native
I have a card game where the user can drag cards around a screen. 我有一个纸牌游戏,用户可以在屏幕上拖动卡片。
How can I detect if the cards have been dragged over other View components? 如何检测卡是否已拖过其他View组件? My draggable card code is like this:
我的可拖动卡片代码是这样的:
// A draggable card
// drag drop code example used: https://github.com/brentvatne/react-native-animated-demo-tinder
// panresponder docs: https://facebook.github.io/react-native/docs/panresponder.html
class Card extends React.Component {
componentWillMount() {
this.state = {
pan: new Animated.ValueXY(),
enter: new Animated.Value(1),
}
this._panResponder = PanResponder.create({
onMoveShouldSetResponderCapture: () => true,
onMoveShouldSetPanResponderCapture: () => true,
onPanResponderGrant: (e, gestureState) => {
Animated.spring(this.state.enter, {
toValue: .75,
}).start()
this.state.pan.setOffset({x: this.state.pan.x._value,
y: this.state.pan.y._value});
this.state.pan.setValue({x: 0, y: 0});
},
onPanResponderMove: Animated.event([
null, {dx: this.state.pan.x, dy: this.state.pan.y},
]),
onPanResponderRelease: (e, {vx, vy}) => {
// do stuff when card released
}
Animated.spring(this.state.enter, {
toValue: 1,
}).start()
this.state.pan.flattenOffset();
var velocity;
if (vx >= 0) {
velocity = clamp(vx, 3, 5);
} else if (vx < 0) {
velocity = clamp(vx * -1, 3, 5) * -1;
}
Animated.spring(this.state.pan, {
toValue: {x: 0, y: toValue},
friction: 4
}).start()
}
})
}
I don't know if this would be the best way to go about it, but I would just get the onLayout
of the target Views to get the x,y,width, and height... 我不知道这是不是最好的方法,但我会得到目标视图的
onLayout
来获得x,y,width和height ......
<View onLayout={({nativeEvent: {layout: {x,y,width,height}}) => { })} />
The coordinates covered by the container would simply be (x, x+width) and (y, y+height) 容器覆盖的坐标只是(x,x +宽度)和(y,y +高度)
onPanResponderGrant
get the location of the draggable: onPanResponderGrant
获取可拖动的位置:
onPanResponderGrant: (e) => {
this.originX = e.pageX - e.locationX;
this.originY = e.pageY - e.locationY;
}
onPanResponderMove
you can do something like this: onPanResponderMove
你可以做这样的事情:
onPanResponderMove: (e, gestureState) => {
const currentX0 = this.originX + gestureState.dx
const currentY0 = this.originY + gestureState.dy
}
The draggable now covers from currentX0
to currentX0 + width
and from currentY0
to currentY0 + height
... draggable现在涵盖从
currentX0
到currentX0 + width
以及从currentY0
到currentY0 + height
......
You can use these values to check to see whether it overlaps with the target view (x, x+width)
and (y, y+height)
您可以使用这些值来检查它是否与目标视图
(x, x+width)
和(y, y+height)
重叠
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.