user3396988
user3396988

Reputation: 55

Use hitTest:withEvent: to return custom object

I want to use - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event to return a custom object on the screen with variables intact.

I've tried:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self.view];
    SLDSlide *selected = (SLDSlide *)[self hitTest:location withEvent:event];
}

and

SLDSlide *selected = (SLDSlide *)[super hitTest:location withEvent:event];

But it's telling me there is no @interface for these methods, and I'm not sure how to write one myself that will return the object I want (SLDSlide, which is a subclass of UIImageView).

Upvotes: 0

Views: 93

Answers (1)

user3386109
user3386109

Reputation: 34839

The following code will find the frontmost SLDSlide object at a given point in the view controller's self.view.

SLDSlide *selected = nil;

for ( UIView *view in self.view.subviews )
{
    if ( [view isKindOfClass:[SLDSlide class]] )
        if ( CGRectContainsPoint( view.frame, location ) )
            selected = (SLDSlide *)view;
}

if ( selected )
    NSLog( @"found one: %@", selected );

Note that if the view hierarchy has multiple levels, then the code would need to search recursively through the hierarchy, so this is just for the case where all of the SLDSlide objects are subviews of the view controller's self.view.

Upvotes: 1

Related Questions