2014-11-06 105 views
0

有没有一种方法可以轻松检测到最近的UIButton到一个水龙头位置?我目前已经划分了一个平底锅手势,但在解决如何解决这个问题时遇到了困难。在过去,我调整了每个按钮的框架大小,以便在按钮之间没有空白区域,但在我目前的情况下这是不可能的。有没有办法检测最近的UIButton来点击位置?

目前,我已经成功地通过了我的子视图,并可以检测到我/不在按钮顶部。但是当我不在按钮上时,如何检测最接近的按钮?

谢谢!

这里是我的代码,用于识别我的UIButtons:

- (UIView *)identifySubview:(NSSet *)touches { 
    CGPoint tapLocation = [[touches anyObject] locationInView:self.view]; 
    for (UIView *view in [self.view viewWithTag:1000].subviews) { 
      for (UITableViewCell *cell in view.subviews) { 
       for (UIView *contentView in cell.subviews) { 
        for (UIButton *button in contentView.subviews) { 
         if ([button isKindOfClass:[UIButton class]]) { 
          CGRect trueBounds = [button convertRect:button.bounds toView:self.view]; 
          if (CGRectContainsPoint(trueBounds, tapLocation)) { 
           return button; 
          } else { 
           //How would I detect the closest button? 
          } 
         } 
        } 
       } 
      } 
    } 
    return nil; 
} 
+0

按钮都是相同的大小? – 2014-11-06 03:28:49

回答

2

失败的直接点击,你可以找到像这样的按钮的中心的最小距离:

// this answers the square of the distance, to save a sqrt operation 
- (CGFloat)sqDistanceFrom:(CGPoint)p0 to:(CGPoint)p1 { 
    CGFloat dx = p0.x - p1.x; 
    CGFloat dy = p0.y - p1.y; 

    return dx*dx + dy*dy; 
} 

- (UIView *)nearestViewIn:(NSArray *)array to:(CGPoint)p { 
    CGFloat minDistance = FLT_MAX; 
    UIView *nearestView = nil; 

    for (UIView *view in array) { 
     CGFloat distance = [self sqDistanceFrom:view.center to:p]; 
     if (distance < minDistance) { 
      minDistance = distance; 
      nearestView = view; 
     } 
    } 
    return nearestView; 
} 

// call ... 
[self nearestViewIn:view.subviews to:tapLocation]; 
+0

OP说明:如果按钮尺寸相同,则只能将按钮中心用作量表。 – 2014-11-06 03:46:40

0

您可以尝试在写 - (空)touchesMoved:(NSSet中*)触及withEvent:方法(的UIEvent *)事件

相关问题