4

I want to move a view with in the parent view I am using UIPanGestureRecognizer to move view. I am using below code.

-(void)move:(UIPanGestureRecognizer *)recognizer {
    CGPoint touchLocation = [recognizer locationInView:self.customeView];

    self.view.center = touchLocation;
}

I want to use locationInView to move view instead of translationInView. Can anyone help me how to move the view with in the parentview using locationInView?

Uttam
  • 236
  • 2
  • 15
  • Is the problem translating the draggable view's coordinates from the subview to the parent view? Or getting it to move at all? – Kyle Clegg Dec 08 '16 at 06:26
  • I have a problem using translationInView so for that I am using locationInView. – Uttam Dec 08 '16 at 06:52

2 Answers2

7

You are on the right track with the UIPanGestureRecognizer. You are likely missing the began and end gesture state handling. Here is a full solution I just put together in sample project (Swift) with a panView as a subclass of the view controller's root view.

class ViewController: UIViewController {

    @IBOutlet weak var panView: UIView!

    // records the view's center for use as an offset while dragging
    var viewCenter: CGPoint!

    override func viewDidLoad() {
        super.viewDidLoad()
        panView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(self.dragView)))
    }

    func dragView(gesture: UIPanGestureRecognizer) {
        let target = gesture.view!

        switch gesture.state {
        case .began, .ended:
            viewCenter = target.center
        case .changed:
            let translation = gesture.translation(in: self.view)
            target.center = CGPoint(x: viewCenter!.x + translation.x, y: viewCenter!.y + translation.y)
        default: break
        }
    }

}
Kyle Clegg
  • 38,547
  • 26
  • 130
  • 141
  • Thank you for your response @Kyle Clegg, but I want to use locationInView inside UIPanGestureRecognizer method. but you are using translation in view in above code – Uttam Dec 08 '16 at 06:51
2

You can try this

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *panView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    //self.panView = self.panView -> self.view . self.panView is direct child of self.view

    UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)];
    [self.panView addGestureRecognizer:panRecognizer];


    // Do any additional setup after loading the view, typically from a nib.
}

-(void)move:(UIPanGestureRecognizer *)recognizer {
    CGPoint centerPoint = [recognizer locationInView:self.view];
    self.panView.center = centerPoint;
}
}
jignesh Vadadoriya
  • 3,244
  • 3
  • 18
  • 29