有几个UIPanGestureRecognizer类的例子。例如我读了
this,我仍然无法使用它…
在我正在工作的nib文件,我有一个UIView(图像上的白色矩形),我想用该类拖动:
并在我的.m文件中我放置:
- (void)setTranslation:(CGPoint)translation inView:(UIView *)view { NSLog(@"Test to see if this method gets executed"); }
并且当我将鼠标拖动到UIView时,该方法不会被执行。我也试过放置:
- (void)pan:(UIPanGestureRecognizer *)gesture { NSLog(@"testing"); }
而且该方法也不执行。也许我错了,但我认为这个方法应该工作像 – (void)touchesMoved:(NSSet *)触摸withEvent:(UIEvent *)事件方法,我只需要放置该方法,它会被调用每当有触摸。
解决方法
我发现教程
Working with UIGestureRecognizers,我认为这是我正在寻找。它帮助我想出了以下解决方案:
-(IBAction) someMethod { UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)]; [panRecognizer setMinimumNumberOftouches:1]; [panRecognizer setMaximumNumberOftouches:1]; [ViewMain addGestureRecognizer:panRecognizer]; [panRecognizer release]; } -(void)move:(id)sender { [self.view bringSubviewToFront:[(UIPanGestureRecognizer*)sender view]]; CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:self.view]; if ([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan) { firstX = [[sender view] center].x; firstY = [[sender view] center].y; } translatedPoint = CGPointMake(firstX+translatedPoint.x,firstY); [[sender view] setCenter:translatedPoint]; if ([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded) { CGFloat veLocityX = (0.2*[(UIPanGestureRecognizer*)sender veLocityInView:self.view].x); CGFloat finalX = translatedPoint.x + veLocityX; CGFloat finalY = firstY;// translatedPoint.y + (.35*[(UIPanGestureRecognizer*)sender veLocityInView:self.view].y); if (UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation])) { if (finalX < 0) { //finalX = 0; } else if (finalX > 768) { //finalX = 768; } if (finalY < 0) { finalY = 0; } else if (finalY > 1024) { finalY = 1024; } } else { if (finalX < 0) { //finalX = 0; } else if (finalX > 1024) { //finalX = 768; } if (finalY < 0) { finalY = 0; } else if (finalY > 768) { finalY = 1024; } } CGFloat animationDuration = (ABS(veLocityX)*.0002)+.2; NSLog(@"the duration is: %f",animationDuration); [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:animationDuration]; [UIView setAnimationCurve:UIViewAnimationCurveEaSEOut]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(animationDidFinish)]; [[sender view] setCenter:CGPointMake(finalX,finalY)]; [UIView commitAnimations]; } }