matt koder
matt koder

Reputation: 117

How to programmatically connect more UIPanGestureRecognizer on more views?

How can I make one UIPanGestureRecognizer? I have multiple views and every one of them has their own UIPanGestureRecognizer. How can I make that, when user holds his finger on one and moves his finger across the screen, the tag of view is changing and also the view, until user lifts his finger from the screen? It' a little bit hard to explain... I hope you will understand. Thank you for your answers.

Upvotes: 0

Views: 79

Answers (1)

Steve Wilford
Steve Wilford

Reputation: 9002

I believe you are trying to create a single pan gesture recogniser that will work with multiple views, and for you to know which view is currently under the users finger during the pan. If this is the case then this should help...

Create a view to act as a container for all the views you want to participate in the pan.

enter image description here

I've given each view it's own colour to make it visually obvious.

enter image description here

I've also added a label to each view to show it's tag.

Hook up a single UIPanGestureRecognizer to the container view and attach it's selector to a method in your view controller class.

- (IBAction)panGestureRecognizerTriggered:(UIPanGestureRecognizer *)recognizer
{
    CGPoint location = [recognizer locationInView:recognizer.view];

    // Find the view that is currently under the user's finger
    for (UIView *view in recognizer.view.subviews) {
        if (CGRectContainsPoint(view.frame, location)) {
            NSLog(@"View %d at %@", (int)view.tag, NSStringFromCGPoint((location)));

            // Found the view, stop searching :)
            break;
        }
    }
}

This method iterates the subviews of the view attached to the gesture recogniser and determines which subview is currently under the users finger, printing the tag and current location.

Admittedly this probably isn't going to be particularly efficient if you're dealing with lots of views but for a simple case such as this it gets the job done.

Upvotes: 1

Related Questions