I have adapted this code from another gentleman on SO. It’s working great so far, but within my app, I plan to have quite a few imageviews/buttons that are moved around. What would be the best way to implement this? Perhaps putting the objects in to arrays and using an enumerator? If anybody else has done something similar, a nudge in the right direction would be very much appreciated!
By the way, they will all have different co-ordinates within the view
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dragGesture:)];
[dragImage addGestureRecognizer:panGesture];
[dragImage setUserInteractionEnabled:YES];
}
#pragma mark -
#pragma mark UIPanGestureRecognizer selector
- (void) dragGesture:(UIPanGestureRecognizer *) panGesture{
CGPoint translation = [panGesture translationInView:self.view];
switch (panGesture.state) {
case UIGestureRecognizerStateBegan:{
originalCentre = dragImage.center;
}
break;
case UIGestureRecognizerStateChanged:{
dragImage.center = CGPointMake(dragImage.center.x + translation.x,
dragImage.center.y + translation.y);
}
break;
case UIGestureRecognizerStateEnded:{
if (((dragImage.center.x >= 280) && (dragImage.center.y >= 280) &&
(dragImage.center.x <= 450) && (dragImage.center.y <= 450))) {
dragImage.center = CGPointMake(300, 300);
[dragImage setUserInteractionEnabled:NO];
break;
}
[UIView animateWithDuration:0.5
animations:^{
dragImage.center = originalCentre;
}
completion:^(BOOL finished){
}];
}
break;
default:
break;
}
[panGesture setTranslation:CGPointZero inView:self.view];
}
-(IBAction)clear{
[UIImageView animateWithDuration:0.5 animations:^{
dragImage.center = CGPointMake(100, 200);
}];
[dragImage setUserInteractionEnabled:YES];
}
Many thanks for taking the time to read this question.
You can use
recognizer.viewto determine which view is being moved. Instead of always changingdrawImage, just userecognizer.view. When the recognizer begins, makes sure to cancel it (by settingenabledtoNOthenYES) if it’s a subview that you don’t want to be drag-and-droppable.You might need to change some of those magic numbers depending on which view is being moved.