Search code examples
iostouchesmoved

How to support touch move across various objects?


I have some labels in my app like this...

enter image description here

What i need to do is, when clicking on a label, just I'm showing label name in the bottom of the screen. It works fine while clicking on each cell separately. But i want to show the changes even the user click on a particular label and move his finger on another label. That is, once he pressed on screen, where ever his finger moves, i want to trace those places and want to show the changes. How can i do this? Please explain briefly.

Thanks in Advance


Solution

  • By default, touch events are only sent to the view they started in. So the easiest way to do what you're trying to do would be to put all of your labels in a container view that intercepts the touch events, and let the container view decide how to handle the events.

    First create a UIView subclass for the container and intercept the touch events by overriding hitTest:withEvent::

    -(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
        // intercept touches
        if ([self pointInside:point withEvent:event]) {
            return self;        
        }
        return nil;
    }
    

    Set that custom class as the class of the container view. Then, implement the various touches*:withEvent: methods on your container view. In your case, something like this should work:

    -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
        // determine which view is under the touch
        UIView* view = [super hitTest:[[touches anyObject] locationInView:self] withEvent:nil];
    
        // get that label's text and set it on the indicator label
        if (view != nil && view != self) {
            if ([view respondsToSelector:@selector(text)]) {
                // update the text of the indicator label
                [[self indicatorLabel] setText:[view text]];
            }
        }
    }