I’m learning iOS and I can’t find how to add drag and drop behavior to a UIView.
I tried:
[_view addTarget:self action:@selector(moved:withEvent:) forControlEvents:UIControlEventTouchDragInside];
It says “no visible interface for UIView declares selector addTarget (etc)“
Also I tried adding a pan gesture recognizer but not sure if that’s what I need
- (IBAction)test:(id)sender {
NSLog(@"dfsdfsf");
}
It’s called, but don’t know how to get the coordinates of the event. What’t the standard, simple way in iOS to register a callback for move events / do drag and drop?
Thanks in advance.
A
UIPanGestureRecognizeris definitely the way to go. If you want the user to drag the view around, you’ll need the “translation” (movement) of the gesture in the superview’s coordinate system:Once you have the translation, you can move (“drag”) the view by changing its
center:Finally, you want to set the pan gesture recognizer’s translation back to zero, so the next time you get the message, it only tells you how much the gesture has moved since the last message:
Here it is all together for easy copy/paste: