iOS - Drag and drop collision detection How to detect when your selected item drags over another subview?

北城余情 提交于 2019-12-04 08:19:19

问题


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.

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?

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

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

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/3947219/ios-drag-and-drop-collision-detection-how-to-detect-when-your-selected-item-dr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!