I want to have a view in which there are vehicles driving around that the user can also drag and drop. What do you think is the best large-scale strategy for doing this? Is it best to get touch events from the views representing the vehicles, or from the larger view? Is there a simple paradigm you've used for drag and drop that you're satisfied with? What are the drawbacks of different strategies?
Press and hold on the first image or link you want to drag, then pull your finger down a little bit. Once you tap and hold on the media you want to move, the usual pop-up menu for sharing options will appear. Ignore that, and jerk your finger down the screen a little without letting go.
Assume you have a UIView
scene with a background image and many vehicles
, you may define each new vehicle as a UIButton
(UIImageView will probably work too):
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; [button addTarget:self action:@selector(imageTouch:withEvent:) forControlEvents:UIControlEventTouchDown]; [button addTarget:self action:@selector(imageMoved:withEvent:) forControlEvents:UIControlEventTouchDragInside]; [button setImage:[UIImage imageNamed:@"vehicle.png"] forState:UIControlStateNormal]; [self.view addSubview:button];
Then you may move the vehicle wherever you want, by responding to the UIControlEventTouchDragInside
event, e.g.:
- (IBAction) imageMoved:(id) sender withEvent:(UIEvent *) event { CGPoint point = [[[event allTouches] anyObject] locationInView:self.view]; UIControl *control = sender; control.center = point; }
It's a lot easier for individual vehicle to handle its own drags, comparing to manage the scene as a whole.
In addition to ohho's answer I've tried similar implementation, but without problem of "fast" drag and centering to drag.
The button initialization is...
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; [button addTarget:self action:@selector(imageMoved:withEvent:) forControlEvents:UIControlEventTouchDragInside]; [button addTarget:self action:@selector(imageMoved:withEvent:) forControlEvents:UIControlEventTouchDragOutside]; [button setImage:[UIImage imageNamed:@"vehicle.png"] forState:UIControlStateNormal]; [self.view addSubview:button];
and method implementation:
- (IBAction) imageMoved:(id) sender withEvent:(UIEvent *) event { UIControl *control = sender; UITouch *t = [[event allTouches] anyObject]; CGPoint pPrev = [t previousLocationInView:control]; CGPoint p = [t locationInView:control]; CGPoint center = control.center; center.x += p.x - pPrev.x; center.y += p.y - pPrev.y; control.center = center; }
I don't say, that this is the perfect solution for the answer. Nevertheless I found this the easiest solution for dragging.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With