views:

71

answers:

1

A UIScrollView contains several UIView objects; how can I tell if a point on the screen not generated by touches is within a specific subview of the scrollview? so far atempts to determine if the point is in the subview always return the first subview in the subviews array of the parent scrollview, ie the coordinates are relative to the scrollview, not the window.

Here's what I tried (edited)

-(UIView *)viewVisibleInScrollView 
{ 
    CGPoint point = CGPointMake(512, 384); 
    for (UIView *myView in theScrollView.subviews) 
    { 
        if(CGRectContainsPoint([myView frame], point)) 
        { 
            NSLog(@"In View"); 
            return myView; 
        } 
    } 
    return nil;
}
+1  A: 

It looks like you're point is relative to the window, and you want it relative to the current view. convertPoint:fromView: should help with this.

There are probably errors here, but it should look something like this:

-(UIView *)viewVisibleInScrollView 
{ 
    CGPoint point = CGPointMake(512, 384); 
    CGPoint relativePoint = [theScrollView convertPoint:point fromView:nil]; // Using nil converts from the window coordinates.
    for (UIView *myView in theScrollView.subviews) 
    { 
        if(CGRectContainsPoint([myView frame], relativePoint)) 
        { 
            NSLog(@"In View"); 
            return myView; 
        } 
    } 
    return nil;
}
Robot K
-1. `-frame` is in the parent's coordinate space. You should either compare against `-bounds`, or convert it to the scroll view's coordinate space *once* and compare against `-frame`.
tc.
Nice catch. I've adjusted the code appropriately.
Robot K
This worked perfectly. Thanks, felt like I was so close.
Kyle
Thanks tc, using the bounds property instead of frame for convertRect parameter fixed my problem
Mutewinter