Skip to content

Instantly share code, notes, and snippets.

@mergesort
Last active August 29, 2015 13:58
Show Gist options
  • Save mergesort/9966920 to your computer and use it in GitHub Desktop.
Save mergesort/9966920 to your computer and use it in GitHub Desktop.
Point within subview
//The subview is a view within an array of views.
//The array of views will be buttons, one of which should be the one being tapped.
//I'm trying to find the subview's position within it's superview, and then check which button is being tapped, and return that.
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
UIView *result = [super hitTest:point withEvent:event];
for (UIView *subview in self.underneathViews)
{
UIView *superview = subview.superview;
CGPoint relativePoint = [superview convertPoint:point toView:subview];
CGRect relativeFrame = [superview convertRect:superview.frame toView:subview];
if (CGRectContainsPoint(relativeFrame, relativePoint))
{
return subview;
}
}
return result;
}
@mergesort
Copy link
Author

//I figured it out. A correct implementation is below, but I'm guessing it can be improved.

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    UIView *result = [super hitTest:point withEvent:event];

    for (UIView *subview in self.underneathViews)
    {
        UIView *superview = subview.superview;
        CGPoint startingPoint = [superview convertPoint:subview.frame.origin toView:self];
        CGRect relativeFrame = CGRectMake(startingPoint.x, startingPoint.y, CGRectGetWidth(subview.frame), CGRectGetHeight(subview.frame));
        if (CGRectContainsPoint(relativeFrame, point))
        {
            return subview;
        }
    }

    return result;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment