Search code examples
iphonexcodeuiimageviewdraggabletouch

iPhone SDK:Trouble Dragging a UIImageView


I am trying to drag a UIImageView around the iphone screen in my app.

Currently The drag functionality I have set up is fine and dragging the image does move it around the screen, the trouble is that you don't have to drag the image view to move it, you can also drag anywhere on the screen and it will move the image. I am new to this platform so I can't really think about what to do to solve this issue. My current code to drag the image is:

 - (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
    CGPoint pt = [[touches anyObject] locationInView:pig];
    startLocation = pt;


}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
    CGPoint pt = [[touches anyObject] locationInView:pig];
    CGRect frame = [pig frame];
    frame.origin.x += pt.x - startLocation.x;
    frame.origin.y += pt.y - startLocation.y;
    [pig setFrame: frame];
}

Any help appreciated. By the way pig is the UIImageView. Also I have noticed that if I set the user interaction of the Image View "pig" to enabled the image is no longer drag able,but when it isn't set to enabled It is.


Solution

  • You can try to subclass UIImageView and implement touchesBegan: and touchesMoved: on it directly. Then in InterfaceBuilder select your subclass for the UIImageView.

    alt text http://img.skitch.com/20090728-xetretcfubtcj7ujh1yc8165wj.jpg

    Oh yes, now you will need to set the user interaction again...