Arcadian
Arcadian

Reputation: 4350

iphone app: drag drop UIImageView

I am trying to do a drag drop in an iphone app. I have a main view that contains multiple layers of views.

I placed:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event    

in the main view but this does not get called. I am able to load a thumbnail image on the view when the user touches for the first time. I try to drag the UIImageView around but the touchesMoved: is not being called.

here is some code: (this is the drag image that is loaded when the user touches the view, it load and is placed underneth the cursor)

[dragImage addTarget:self action:@selector(endDrag) forControlEvents:UIControlEventTouchUpOutside];
[dragImage addTarget:self action:@selector(endDrag) forControlEvents:UIControlEventTouchUpInside];
[dragImage addTarget:self action:@selector(endDrag) forControlEvents:UIControlEventTouchDragInside];

Upvotes: 0

Views: 3181

Answers (2)

Bijoy Thangaraj
Bijoy Thangaraj

Reputation: 5546

What you can do is place the UIImageView inside a UIControl (which will respond to UIControlEventTouchDragInside).

UIControl *dragImageControl = [[UIControl alloc] initWithFrame:dragImageView.frame];
        [dragImageControl addSubview:dragImageView];

[self.view addSubview:dragImageControl];

[dragImageControl addTarget:self action:@selector(imageTouch:withEvent:) forControlEvents:UIControlEventTouchDown];
[dragImageControl addTarget:self action:@selector(imageMoved:withEvent:) forControlEvents:UIControlEventTouchDragInside];

and in imageMoved, you can have this code:

- (IBAction) imageMoved:(id) sender withEvent:(UIEvent *) event
{
    CGPoint point = [[[event allTouches] anyObject] locationInView:self.view];
    UIControl *control = sender;
    control.center = point;
}

Upvotes: 1

Ecarrion
Ecarrion

Reputation: 4950

This is what I do to drag an image around the screen:

UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)];
[panRecognizer setMinimumNumberOfTouches:1];
[panRecognizer setMaximumNumberOfTouches:1];
[panRecognizer setDelegate:self];
[imageView_ addGestureRecognizer:panRecognizer];

And then:

-(void)move:(id)sender {

    CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:self.view];

    if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan) {

        firstX = [[sender view] center].x;
        firstY = [[sender view] center].y;
    }

    translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY+translatedPoint.y);
    [[sender view] setCenter:translatedPoint];

}

Upvotes: 1

Related Questions