Search code examples
iosobjective-cuiviewcgrectcgpoint

Best choice when detecting whether a view's point is inside another view?


So I've found 3 ways to make this happen.

  1. convertPoint:toView: convertPoint:fromView: convertRect:toView: convertRect:fromView:

  2. Bool CGRectContainsPoint(CGRect rect, CGPoint point);

  3. BOOL isPointInsideView = [aView pointInside:aPoint withEvent:nil];

They all seem to do the same but I might be wrong. You check if a point is inside a certain view considering its frame then get either true or false.

Does it not matter which one of them I end up using or should I be aware of issues that might arise..?


Solution

  • You should be aware of what each method is used for:

    The docs for pointInside:withEvent: say

    point | A point that is in the receiver’s local coordinate system (bounds).

    Apart from that the method probably does simply call CGRectContainsPoint with the passed point and the bounds frame.

    CGRectContainsPoint simply does the math of checking the x and y coordinates against the origin and size. Simple math, but once again both have to be in the same coordinate system since neither the rect nor the point contain any information about their respective coordinate system, they are absolute values.

    The convert* functions offer you the ability to transform the CGPoint which is relative to the receiver's coordinate system into some other relative coordinate system.

    To understand what each method is good for, you have to understand what the different CGRects mean, frame and bounds in particular: this answer is THE way to go for that.

    After understanding what the different properties mean it should be easy to pick the correct function.

    TL;DR: the convert* methods offer you the ability to transform CGPoints between coordinate systems. The other two options operate within one certain fixed coordinate system. It is your job to pick the one you need in your particular case.

    For example you might have to transform a point first and then perform the hit detection.