我依靠locationOfTouch
( not translationInView
) 和不同state
的手势来实现类似的东西。
就我而言,我必须使用该子视图内的锚定按钮(为 UIPanGestureRecognizer 注册的按钮)移动子视图。手势完成后,我的视图再次捕捉到屏幕的左壁(y 轴移动)。
- (void)moveViewWithGestureRecognizer:(UIPanGestureRecognizer *)gestureRecognizer
{
// Need to make below calculation for other orientations. Until then this is not allowed.
if (self.interfaceOrientation != UIInterfaceOrientationPortrait) return;
static CGFloat initialCenterPointX = 0;
const CGPoint deltaPoint = CGPointMake(self.view.bounds.size.width/2 - gestureRecognizer.view.superview.center.x, self.view.bounds.size.height/2 - gestureRecognizer.view.superview.center.y);
if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
initialCenterPointX = self.view.center.x;
}
else if (gestureRecognizer.state == UIGestureRecognizerStateChanged) {
CGPoint location = [gestureRecognizer locationOfTouch:0 inView:self.view];
NSLog(@"gestureRecognizer.view = %@ location = %f, %f", gestureRecognizer.view, location.x, location.y);
CGFloat proposedCenterPointX = self.view.frame.origin.x + location.x;
CGFloat proposedCenterPointY = self.view.frame.origin.y + deltaPoint.y + location.y;
CGPoint newCenterLocation = CGPointZero;
newCenterLocation.x = MAX(proposedCenterPointX, self.view.bounds.size.width/2);
newCenterLocation.y = MAX(proposedCenterPointY, self.view.bounds.size.height/2);
self.view.center = newCenterLocation;
}
else {
[UIView animateWithDuration:0.2 animations:^{
self.view.center = CGPointMake(initialCenterPointX, self.view.center.y);
}];
}
}