iOS - 拖放碰撞检测如何检测所选项目何时拖动到另一个子视图?

时间:2022-04-01 00:19:55

We are adding drag and drop functionality to what is to become a sports field with positions for players.

我们正在添加拖放功能,以便成为一个有球员位置的运动场。

The positions are mapped out using Interface Builder with each being a separate UIImageView.

使用Interface Builder映射出位置,每个位置都是一个单独的UIImageView。

We want to be able to drag player images from bench positions from the side of the screen onto positions on the field.

我们希望能够将玩家图像从屏幕一侧的工作台位置拖动到场地上的位置。

How best can we detect when the selected player which is being moved around collides with an existing gamePosition imageView?

我们如何最好地检测被移动的所选玩家何时与现有的gamePosition imageView碰撞?

We are looking for a way to detect if there is a view or ImageView under the current location.

我们正在寻找一种方法来检测当前位置下是否存在视图或ImageView。

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
  UITouch *touch = [[event allTouches] anyObject];
  CGPoint location = [touch locationInView:touch.view];
  tile1.center = location;  

  if gamePositionExistsAtCurrentLocation(location) { //want something like this
    [tile1 setBackgroundColor:[UIColor blueColor]]; 
  } else {
   [tile1 setBackgroundColor:[UIColor yellowColor]]; 
  }
}

2 个解决方案

#1


14  

check if the frame of the item you are moving intersects with the frame from on of your subviews

检查您正在移动的项目的框架是否与子视图的框架相交

for (UIView *anotherView in self.subviews) {
    if (movingView == anotherView)
        continue;
    if (CGRectIntersectsRect(movingView.frame, anotherView.frame)) {
        // Do something
    }
}

If I were you, I would add all game relevant items to an NSArray and for-loop through this. So you don't detect collisions with subviews that have nothing to do with your game like labels and so on.

如果我是你,我会将所有与游戏相关的项目添加到NSArray并通过此循环。因此,您不会检测与您的游戏无关的子视图(如标签等)的碰撞。

#2


4  

Also might want to consider view.center with CGRectContainsPoint()

也可能想用CGRectContainsPoint()来考虑view.center

#1


14  

check if the frame of the item you are moving intersects with the frame from on of your subviews

检查您正在移动的项目的框架是否与子视图的框架相交

for (UIView *anotherView in self.subviews) {
    if (movingView == anotherView)
        continue;
    if (CGRectIntersectsRect(movingView.frame, anotherView.frame)) {
        // Do something
    }
}

If I were you, I would add all game relevant items to an NSArray and for-loop through this. So you don't detect collisions with subviews that have nothing to do with your game like labels and so on.

如果我是你,我会将所有与游戏相关的项目添加到NSArray并通过此循环。因此,您不会检测与您的游戏无关的子视图(如标签等)的碰撞。

#2


4  

Also might want to consider view.center with CGRectContainsPoint()

也可能想用CGRectContainsPoint()来考虑view.center