Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS dragging UIImageView

Ok, so I have always wondered how do I actually pick up an image view and drag it. I was planning when I drag an image view and when user places it to correct location it locks there. I really don't have idea how to do this and it has bothered me for sometime.

Thanks so much in advance!

like image 582
Samuli Lehtonen Avatar asked Jun 27 '11 22:06

Samuli Lehtonen


2 Answers

Or you can use a UIPanGestureRecognizer if you don't want to subclass the view and handle touches yourself.

Create a pan recognizer in any class (e.g. view controller) and add it to your view:

UIPanGestureRecognizer * panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                                                 action:@selector(handlePanGesture:)];
[myDraggedView addGestureRecognizer:panRecognizer];

And then simply:

- (void)handlePanGesture:(UIPanGestureRecognizer *)gestureRecognizer
{
    CGRect frame = myDraggedView.frame;
    frame.origin = [gestureRecognizer locationInView:myDraggedView.superview];
    myDraggedView.frame = frame;
}

If you like Interface Builder as much as me you can also just drag a pan gesture recognizer over your image view, and then connect the recognizer to the handlePanGesture: that should be declared as an IBAction instead of void.

like image 157
Rivera Avatar answered Oct 05 '22 23:10

Rivera


If you're one for reading, then check out the UIResponder Class Reference, and, in particular, touchesBegan and touchesMoved.

like image 26
PengOne Avatar answered Oct 06 '22 00:10

PengOne