【问题标题】:drag images only when image is touched仅在触摸图像时拖动图像
【发布时间】:2014-04-01 19:14:06
【问题描述】:

我在屏幕上拖动了一张图像,但是无论我触摸屏幕的哪个位置,图像都会出现在我的手指上并开始拖动,对于我观看的所有视频以及所有博客和文章,人们正在展示的所有内容都是怎么做……这不是我想要的……我想要的是只有在我触摸图像时才开始拖动图像……这是我的代码

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event

{

UITouch *Drag = [ [  event allTouches ] anyObject ];
Dot.center = [ Drag locationInView: self.view ];

[self checkCollison];

}

谢谢

【问题讨论】:

  • 使用 UIPangesture 代替这个

标签: ios xcode5


【解决方案1】:

在您的 .h 中

IBOutlet UIImageView * YOURIMAGE;

在你的 .m 中

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    if ([touch view] == YOURIMAGE) {
        YOURIMAGE.center = [touch locationInView:self.view];
    }
}

【讨论】:

  • 我喜欢它的简单性,但它不起作用..如果我把你的代码放在点中,它根本不动......
【解决方案2】:

不要使用-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 方法,而是使用UIPanGestureRecognizer

创建平移手势并将其添加到您的UIImageView,例如:

UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleDrag:)];
[yourImageView addGestureRecognizer:panGesture];

并将选择器方法编写如下:

- (void)handleDrag:(UIPanGestureRecognizer*)recognizer
{

    CGPoint translation = [recognizer translationInView:recognizer.view];
    CGPoint velocity    = [recognizer velocityInView:recognizer.view];
    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
                                     recognizer.view.center.y + translation.y);

    if (recognizer.state == UIGestureRecognizerStateBegan)
    {
       // start tracking movement
    }
    else if (recognizer.state == UIGestureRecognizerStateEnded)
    {
         // You can change position here, with animation
    }
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多