【问题标题】:Is there another way to detect views when dragging other View over it?将其他视图拖到上面时,是否有另一种方法来检测视图?
【发布时间】:2013-02-13 03:37:30
【问题描述】:

我使用平移手势在拖动线中拖动多视图,例如:iOS - Drag and drop collision detection How to detect when your selected item drags over another subview?

我的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    for (UIView *aView in self.view.subviews) {
        [self addGestureRecognizersToPiece:aView];
    }
}

- (void)addGestureRecognizersToPiece:(UIView *)piece
{
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panPiece:)];
    [piece addGestureRecognizer:panGesture];
}



- (void)panPiece:(UIPanGestureRecognizer *)gestureRecognizer
{
    CGPoint dragingPoint = [gestureRecognizer locationInView:self.view];

    for (UIView *aView in self.view.subviews) {
        if (CGRectContainsPoint([aView frame], dragingPoint)) {
                aView.center = dragingPoint;
        }
    }

}

我有这么多子视图,所以我不想循环 self.view 中的所有子视图,我只想检测拖动线中的匹配视图。怎么做?

如果我使用 [gestureRecognizer 视图],我只会得到第一个视图。

提前感谢您的帮助!

【问题讨论】:

  • 嗯,正如我所看到的,您想找到正确的视图而不实际找到它。我的意思是,如果确实存在一些内置函数,它会在引擎盖下“循环所有子视图”以找到正确的。您可以做的是将不同的手势识别器附加到不同的视图,这还不够。您也可以尝试使用touchesBegan:withEvent‎:touchesMoved:withEvent:。像在视图的touchesBegan 中设置一些像“我被感动”这样的标志,然后(在PanPiece 中)只需搜索带有该标志的视图。您仍将循环浏览视图,但效率更高。

标签: ios uiview uigesturerecognizer


【解决方案1】:

如果你只是想要更简单的代码,你可以使用 UIView 的hitTest:withEvent: 方法在触摸位置找到视图:

- (void)panPiece:(UIPanGestureRecognizer *)gestureRecognizer
{
    CGPoint draggingPoint = [gestureRecognizer locationInView:self.view];
    UIView *hitView = [self.view hitTest:draggingPoint withEvent:nil];
    if (hitView.superview == self.view)
        hitView.center = draggingPoint;
}

这假设子视图本身没有(交互式)子视图。

【讨论】:

  • 感谢您的回答!拖动任何视图时看起来都不错,但是在更改中心时,只有 1 个视图处于活动状态。我还在尝试一些改变。
【解决方案2】:

你所拥有的是最好的(即最简单的)方法。除非您注意到性能问题,否则不要担心。

您可以进行一些改进:

  1. 如果您只对某些视图感兴趣(您在拖动线上提到了那些,我不确定那是什么),然后在开始之前将这些视图添加到数组中,然后循环遍历该数组。
  2. 一旦找到目标就跳出循环(使用break;)。
  3. 存储最后一次点击视图并首先检查 - 在很多情况下,它不会与上次调用该方法时发生变化。

【讨论】:

    【解决方案3】:

    您可以通过使用 CGRectIntersectsRect(<#CGRect rect1#>, <#CGRect rect2#>)

    【讨论】:

      猜你喜欢
      • 2012-10-10
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-14
      相关资源
      最近更新 更多