I have several UIViews that the user should be able to drag & drop. I use UIPanGestureRecognizer to manage the d&d action (see code below). The d&d action is working fine, but when I start dragging another UIView, the one that I just dropped is jumping back to its original position.
- (void)handlePan:(UIPanGestureRecognizer *)recognizer {
CGPoint translation = [recognizer translationInView:self.view];
switch (recognizer.state) {
case UIGestureRecognizerStateBegan:
for (UIView* checkView in dragAndDropImageViewsArray) {
if (checkView == recognizer.view) {
[checkView.superview bringSubviewToFront:checkView]; //this is done to make sure the currently dragged object is the top one
}
}
break;
case UIGestureRecognizerStateChanged:
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x, recognizer.view.center.y + translation.y);
break;
case UIGestureRecognizerStateEnded:
NSLog(@"UIGestureRecognizerStateEnded");
break;
default:
break;
}
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}
I tried several things that "sloved" the problem but caused other problems:
- Cancel Auto-Layout: That totally solves it but now I have to start calculate and manage object locations and sizes for different devices and orientations.
- Use layer.zPosition instead of bringSubviewToFront: that makes objects appear above other objects while apparently avoiding the "jump back", but does not allow me to change the hierarchy between the different draggable objects.
I started deepening my understanding about Auto Layout, but it gets very complicated when it seems to me that what I'm looking for should be very simple; I saw many methods that deal with performing a "re-auto-layouting", but I'm not clear about how to work with them.
Is there a simple solution here? like calling a method that overrides the IB Auto-Layout constrains and redefine them according to the UIView new position?
Any assistance would be very musch appreciated.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…