@implementation DraggableImage
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
// Retrieve the touch point
CGPoint pt = [[touches anyObject] locationInView:self];
startLocation = pt;
[[self superview] bringSubviewToFront:self];
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
// Move relative to the original touch point
CGPoint pt = [[touches anyObject] locationInView:self];
CGRect frame = [self frame];
frame.origin.x += pt.x - startLocation.x;
frame.origin.y += pt.y - startLocation.y;
[self setFrame:frame];
}
@end
Lastly open the view controller where you want the draggable image and add the draggable image programmatically to your view. Make sure you change the @"block.png" to your image and the x, y, width and height coordinates inside of CGRectMake to your image location:
- (void)viewDidLoad {
[super viewDidLoad];
DraggableImage *dragger;
CGRect dragRect = CGRectMake(10, 250, 100, 10);
dragger = [[DraggableImage alloc] initWithFrame:dragRect];
[dragger setImage:[UIImage imageNamed:@"block.png"]];
[dragger setUserInteractionEnabled:YES];
[self.view addSubview:dragger];
}