rptwsthi
rptwsthi

Reputation: 10172

How to Get viewAtLocation:(CGPoint)location?

Now a days in several of my iOS applications I need to get adjacent views recursively. I wonder if we have any thing like viewAtLocation:(CGPoint)location? Or there's any way we can implement it.

I have used several ways like C array id matrix[row][col] with location decided by size as index value, and retrieving all subview then checking for location one by one in a loop etc. Although these are working for me but these doesn't seems good or say appropriate to me. So what else we can have?

Upvotes: 0

Views: 1046

Answers (2)

Abid Hussain
Abid Hussain

Reputation: 1549

The following code will do it for you bro

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

Upvotes: 1

Mike Weller
Mike Weller

Reputation: 45598

It's best to use the standard hitTest:withEvent which will handle things like ignoring a view if it's opacity is 0.0. The documentation says to pass in nil for the event when calling it manually.

This will also behave correctly for any views which have extended their bounds using pointInside:withEvent:.

Upvotes: 3

Related Questions