【问题标题】:Is there a way to detect closest UIButton to tap location?有没有办法检测最近的 UIButton 以点击位置?
【发布时间】:2014-11-06 03:19:56
【问题描述】:

有没有一种方法可以轻松检测到离点击位置最近的 UIButton?我目前已经对平移手势进行了子类化,但只是在弄清楚如何处理这个问题上遇到了麻烦。过去,我调整了每个按钮框架的大小,以便按钮之间没有空白空间,但在我目前的情况下这是不可能的。

目前,我已经成功循环浏览了我的子视图,并且可以检测到我何时/不在按钮之上。但是,当我不在按钮上时,如何检测最近的按钮?

谢谢!

这是我识别 UIButton 的代码:

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

【问题讨论】:

  • 按钮大小都一样吗?

标签: ios objective-c touch-event uipangesturerecognizer


【解决方案1】:

如果直接命中失败,您可以找到到按钮中心的最小距离,如下所示:

// 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];

【讨论】:

  • OP注意:如果按钮大小相同,您只能使用按钮中心作为量规。
【解决方案2】:

您可以尝试写入 - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    相关资源
    最近更新 更多