gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:55:24 25 4
gpt4 key购买 nike

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

目前,我已经成功地遍历了我的 subview ,并且可以检测到我何时位于/不位于按钮之上。但是,当我不在按钮上时,如何检测到最近的按钮?

谢谢!

这是我用于识别 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;
}

最佳答案

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

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

关于ios - 有没有办法检测最接近点击位置的 UIButton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26771169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com