When the UILongPressGestureRecognizer begins recognizing I'd like to move the view to another view but when this happens the state changes to cancelled.
if (longPressGestureRecognizer.state == UIGestureRecognizerStateBegan) {
[cellView removeFromSuperview];
[self.anotherView addSubview:cellView];
}
Is there any way to preserve the gesture recognizer?
CodePudding user response:
Remove this line:
[cellView removeFromSuperview];
When you execute:
[self.anotherView addSubview:cellView];
UIKit will move the cellView
from its current superview automatically and add it to anotherView
.
That should prevent losing the state of the gesture recognizer.
Here's a quick example:
#import "LongPressViewController.h"
@interface LongPressViewController ()
{
UIView *blueView;
UIView *redView;
UIView *yellowView;
}
@end
@implementation LongPressViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = UIColor.systemBackgroundColor;
blueView = [UIView new];
redView = [UIView new];
yellowView = [UIView new];
blueView.backgroundColor = UIColor.systemBlueColor;
redView.backgroundColor = UIColor.systemRedColor;
yellowView.backgroundColor = UIColor.systemYellowColor;
blueView.frame = CGRectMake(80, 100, 240, 240);
redView.frame = CGRectOffset(blueView.frame, 0, 260);
yellowView.frame = CGRectMake(20, 20, 80, 80);
[blueView addSubview:yellowView];
[self.view addSubview:blueView];
[self.view addSubview:redView];
UILongPressGestureRecognizer *g = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(lpHandler:)];
[yellowView addGestureRecognizer:g];
}
- (void)lpHandler:(UILongPressGestureRecognizer *)longPressGestureRecognizer {
CGPoint p = [longPressGestureRecognizer locationInView:yellowView];
switch (longPressGestureRecognizer.state) {
case UIGestureRecognizerStateBegan:
[redView addSubview:yellowView];
break;
case UIGestureRecognizerStateChanged:
NSLog(@"Changed: %@", [NSValue valueWithCGPoint:p]);
break;
case UIGestureRecognizerStateEnded:
NSLog(@"Ended");
break;
default:
break;
}
}
@end
yellowView
will start as a subview of blueView
. When you long-press, it will "jump" to - and become a subview of - redView
.
Keep the touch down, and as you drag you'll see the continuous logging of the touch location (relative to yellowView
).
When you release the touch, we log "Ended"