Drag a view with the speed of the UIPanGestureRecognizer gesture

0

I have a method that drags me a view as I slide my finger on the screen. For this I use UIPanGestureRecognizer . In the method I increase the position x of the view point to point, but I'm interested in moving it according to the speed with which I move my finger. If I slowly move the movement if it fits if I do it point by point but if I slide more quickly the increments I do not know how to do them. I have tried with the locationInView or velocity method of UIPanGestureRecognizer but I have not implemented it well.

CGPoint touchLocation = [panGestureRecognizer locationInView:self.view];
CGPoint velocity = [panGestureRecognizer velocityInView:self.view];

posX = posX + 1;

self.view would be the main view, posx is the position of the view that I move according to the event.

    
asked by Popularfan 11.01.2017 в 17:33
source

1 answer

2

It's very simple. First of all we create a UIView of example to illustrate the result:

// Añadimos view de ejemplo
- (void)createView {

    // View
    UIView *draggable = [[UIView alloc] initWithFrame:CGRectMake(100.0, 100.0, 200.0, 200.0)];
    draggable.backgroundColor = [UIColor redColor];
    [self.view addSubview:draggable];

    // Gesture
    UIPanGestureRecognizer *gesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(draggableAction:)];
    [draggable addGestureRecognizer:gesture];

}

Next, we need the method that will be executed when doing the UIPanGestureRecognizer :

// Acción al arrastrar la view
- (void)draggableAction:(UIPanGestureRecognizer *)recognizer {

    // Cogemos la posición del gesto respecto de la view
    CGPoint touchCenter = [recognizer locationInView:self.view];

    // Modificamos el centro de la view
    recognizer.view.center = touchCenter;

}

This way, dragging from within the UIView will move along with the center of the drag.

    
answered by 11.01.2017 / 18:10
source