如何获取viewAtLocation:(CGPoint)位置?

时间:2012-12-05 12:12:14

标签: iphone objective-c ios ios4 uiview

现在,在我的几个iOS应用程序中,我需要递归地获取相邻视图。我想知道我们是否有像viewAtLocation:(CGPoint)location这样的东西?或者我们可以采用任何方式实现它。

我使用过多种方式,比如C array id matrix[row][col],其位置由size决定为索引值,然后检索所有subview然后在循环中逐个检查location等。虽然这些对我有用,但这些对我来说似乎不好或不合适。那么我们还能拥有什么?

2 个答案:

答案 0 :(得分:3)

最好使用标准hitTest:withEvent,如果它的不透明度为0.0,它将处理忽略视图的事情。文档说明在手动调用时传入nil

对于使用pointInside:withEvent:扩展其边界的任何视图,这也会正常运行。

答案 1 :(得分:1)

以下代码将为您做到这一点

UIView *view = <Your View>;
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[view addGestureRecognizer:recognizer];
[recognizer release];

- (void)handleSingleTap:(UITapGestureRecognizer*)recognizer{

    CGPoint p = [recognizer locationInView:recognizer.view];
    for (UIView *v in recognizer.view.subviews) {
        if (CGRectContainsPoint(v.frame, p)) {
            NSLog(@"view Found with frame %@",NSStringFromCGRect(v.frame));
            //If your views doesn't overlap then break from here
            break;
        }
    }
}