如何在不破坏手势识别器的情况下将视图移动到另一个视图?

How can I move a view to another view without breaking the gesture recognizer?

当 UILongPressGestureRecognizer 开始识别时,我想将视图移动到另一个视图,但当这种情况发生时,状态变为已取消。

if (longPressGestureRecognizer.state == UIGestureRecognizerStateBegan) {
    
    [cellView removeFromSuperview];
    
    [self.anotherView addSubview:cellView];
}

有什么方法可以保留手势识别器吗?

删除这一行:

[cellView removeFromSuperview];

当你执行:

[self.anotherView addSubview:cellView];

UIKit 会自动将 cellView 的当前超级视图中移出并添加到 anotherView.

应该防止丢失手势识别器的状态。

这是一个简单的例子:

#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 将作为 blueView 的子视图启动。当你 long-press 时,它会“跳转”到 - 并成为 - redView.

的子视图

保持触摸向下,拖动时您会看到触摸位置的连续记录(相对于 yellowView)。

当您释放触摸时,我们记录“结束”