gpt4 book ai didi

iphone - 如何使用 UIPanGestureRecognizer 移动对象? iPhone/iPad

转载 作者:IT老高 更新时间:2023-10-28 11:23:50 31 4
gpt4 key购买 nike

UIPanGestureRecognizer 类有几个示例。例如我读过 this而且我仍然无法使用它...

在我正在处理的 nib 文件上,我有一个 UIView(图像上的白色矩形),我希望用该类拖动它:

enter image description here

在我放置的 .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 *)touches withEvent:(UIEvent *)event 方法一样工作,我只需要放置该方法,它就会每当有触摸时都会被调用。

我做错了什么?也许我必须与该方法建立联系?如果是这样,我该怎么做?

最佳答案

我找到了教程 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:(UIPanGestureRecognizer*)sender {
[self.view bringSubviewToFront:sender.view];
CGPoint translatedPoint = [sender translationInView:sender.view.superview];

if (sender.state == UIGestureRecognizerStateBegan) {
firstX = sender.view.center.x;
firstY = sender.view.center.y;
}


translatedPoint = CGPointMake(sender.view.center.x+translatedPoint.x, sender.view.center.y+translatedPoint.y);

[sender.view setCenter:translatedPoint];
[sender setTranslation:CGPointZero inView:sender.view];

if (sender.state == UIGestureRecognizerStateEnded) {
CGFloat velocityX = (0.2*[sender velocityInView:self.view].x);
CGFloat velocityY = (0.2*[sender velocityInView:self.view].y);

CGFloat finalX = translatedPoint.x + velocityX;
CGFloat finalY = translatedPoint.y + velocityY;// translatedPoint.y + (.35*[(UIPanGestureRecognizer*)sender velocityInView:self.view].y);

if (finalX < 0) {
finalX = 0;
} else if (finalX > self.view.frame.size.width) {
finalX = self.view.frame.size.width;
}

if (finalY < 50) { // to avoid status bar
finalY = 50;
} else if (finalY > self.view.frame.size.height) {
finalY = self.view.frame.size.height;
}

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];
}
}

关于iphone - 如何使用 UIPanGestureRecognizer 移动对象? iPhone/iPad,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6672677/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com