有没有办法检测最近的UIButton点击位置?

时间:2014-11-06 03:19:57

标签: ios objective-c ontouchevent uipangesturerecognizer

有没有办法轻松检测到最近的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;
}

2 个答案:

答案 0 :(得分: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];

答案 1 :(得分:0)

您可以尝试写入 - (void)touchesMoved:(NSSet *)触及withEvent:(UIEvent *)事件

相关问题