【问题标题】:iOS - Drag and drop collision detection How to detect when your selected item drags over another subview?iOS - 拖放碰撞检测如何检测您选择的项目何时拖过另一个子视图?
【发布时间】:2011-04-26 05:20:25
【问题描述】:

我们正在为即将成为具有球员位置的运动场添加拖放功能。

使用 Interface Builder 绘制位置,每个位置都是一个单独的 UIImageView。

我们希望能够将球员图像从屏幕一侧的替补位置拖到场上的位置上。

我们如何才能最好地检测到正在移动的选定玩家何时与现有的 gamePosition imageView 发生碰撞?

我们正在寻找一种方法来检测当前位置下是否存在视图或 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]]; 
  }
}

【问题讨论】:

    标签: iphone drag-and-drop ios collision-detection


    【解决方案1】:

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

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

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

    【讨论】:

    • 所以我的想法是,每次我移动时,我都会遍历一组对象,看看它们是否与我当前的位置匹配(但正如你提到的那样使用框架)?
    • 是否有任何苹果提供的方法可以让我知道当前哪些子视图与指定点相交?
    【解决方案2】:

    还可以考虑view.centerCGRectContainsPoint()

    【讨论】:

    • 该方法采用以下格式:CGRectContainsRect(, ) 如何将view.center或location.centre表示为一个矩形?
    • 不是 CGRectContainsRect(),我是说使用 CGRectContainsPoint()。除非您的放置矩形明显更大,否则不要使用第一个,因为只有当一个矩形完全在另一个矩形内时才会返回 true。
    • 对不起,我的错......错过了你的帖子......谢谢。整理出来。您的建议很有帮助。
    猜你喜欢
    • 2012-10-24
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    相关资源
    最近更新 更多