1

我想知道你们是否有一个示例代码添加并在触摸时移动 UIImageView 并检测是否有 UIImageView ,所以我不能在它上面添加 UIImageView 。

编辑:更清晰的问题 1. 我想在触摸视图时添加一个杯子(UIImageView),但不想让杯子(UIImageView)堆叠。

  1. 我想移动 UIImageView 但如果那里有 UIImageView 会弹回原来的位置,所以它不会堆叠 UIImageView 已经在那里。

感谢您阅读我的问题并感谢您的帮助

干杯

德斯

4

2 回答 2

2

您可以将 UIPanGestureRecognizer 添加到 UIImageView 以处理拖动,如下所示。

UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)];
[panRecognizer setMinimumNumberOfTouches:1];
[panRecognizer setMaximumNumberOfTouches:1];
[panRecognizer setDelegate:self];
[imageView addGestureRecognizer:panRecognizer];

实现以下方法:

    -(void)move:(id)sender {

    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+translatedPoint.y);
      [[sender view] setCenter:translatedPoint];

    }

结合以上内容,您可以使用 CGRectIntersectsRect 来查找它是否与另一个杯子相交。

BOOL isIntersecting = CGRectIntersectsRect ([cup1 frame],[cup2 frame]);

您必须包装功能以考虑所有杯子,但这让您了解如何完成您想要做的事情。

于 2012-06-01T00:44:19.350 回答
1

这应该让你去......</p>

在头文件中创建两个 ivars:

UIImageView *myImageView1;
UIImageView *myImageView2;

接下来的两个方法将在您的实现文件中:

-(void)initImagesAndPanGesture
{
    UIImage *img = [UIImage imageNamed:@"image1.png"];
    myImageView1 = [[UIImageView alloc]initWithImage:img];
    [myImageView1 setFrame:CGRectMake(300, 800, 100, 100)];
    [myImageView1 setUserInteractionEnabled:YES];
    UIPanGestureRecognizer *recognizer1 = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan1:)];
    [myImageView1 addGestureRecognizer:recognizer1];
    [self.view addSubview:myImageView1];

    img = [UIImage imageNamed:@"image2.png"];
    myImageView2 = [[UIImageView alloc]initWithImage:img];
    [myImageView2 setFrame:CGRectMake(500, 800, 100, 100)];
    [myImageView2 setUserInteractionEnabled:YES];
    recognizer1 = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan1:)];
    [myImageView2 addGestureRecognizer:recognizer1];
    [self.view addSubview:myImageView2];
}

-(void)handlePan1:(UIPanGestureRecognizer *)recognizer
{
    if (!(CGRectIntersectsRect(myImageView1.frame, myImageView2.frame)))
    {
        CGPoint translation = [recognizer translationInView:self.view];
        recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x, 
                                         recognizer.view.center.y + translation.y);

        [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
    }
    else 
    {
        NSLog(@"intersect!");
    }
}
于 2012-06-01T00:51:19.340 回答