1

I know how to get the position touched, so now i have a CGPoint with the touched position. What's the best way to find out if the touch is over a UIView or not? I know of the method of:

if touchpoint.x > frame.origin.x && touchpoint.x < frame.size.width + frame.origin.x

etc., but is this the best way of going about it?

Andrew
  • 15,935
  • 28
  • 121
  • 203

3 Answers3

5

If you simply want to know if a point is inside the bounds of a view, you can use the pointInside:withEvent: method.

CGPoint touchPoint = [theTouch locationInView:theView];
// If the point was retrieved for a different view, it must be converted to the coordinate space of the destination view using convertPoint:fromView:
if([theView pointInside:touchPoint withEvent:nil]) {
    NSLog(@"point inside");
}
ughoavgfhw
  • 39,734
  • 6
  • 101
  • 123
3

Ugh's answer covers views, which I believe is what you want; if you have an arbitrary CGRect, you can use CGRectContainsPoint:

BOOL isInside = CGRectContainsPoint(myRect, touchPoint);
jscs
  • 63,694
  • 13
  • 151
  • 195
0

Yes, CGRectContainsPoint will save you from writing so many comparision equations.

MobileSoul
  • 31
  • 2