Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

determine if point on screen is within specific UIScrollView subview

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;
}
like image 931
Kyle Avatar asked Sep 28 '10 20:09

Kyle


2 Answers

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;
}
like image 132
Kris Markel Avatar answered Nov 11 '22 05:11

Kris Markel


Here's what I do:

@implementation UIScrollView (FOO)
- (id)foo_subviewAtPoint:(CGPoint)point
{
    point.x += self.contentOffset.x;
    for (UIView *subview in self.subviews) {
        if (CGRectContainsPoint(subview.frame, point)) {
            return subview;
        }
    }
    return nil;
}
@end

And here's how I use it:

CGPoint center = [scrollView convertPoint:scrollView.center fromView:scrollView.superview];
UIView *view = [scrollView foo_subviewAtPoint:center];

Some things to note:

  • The point passed to foo_subviewAtPoint: is expressed in the coordinate system of the scroll view. This is why in the code above I have to convert center to that coordinate system from that of its superview.
  • I'm using iOS 6.1+ with layout constraints. I've never tested this code with anything else, so YMMV.
like image 2
Gregory Higley Avatar answered Nov 11 '22 04:11

Gregory Higley