ios – 当longPress执行时启用UIPanGestureRecognizer

我想在customView执行longPress时在customView上启用UIPanGestureRecognizer.

(我希望当你longPress customView时,customView将切换到“移动模式”,你可以通过拖动移动customView.)

但是在这段代码中,只有longPressAction:调用. panAction:没跟.
如何修复它以启用PanAction:?

- (void)viewDidLoad
{
    [self.view addSubview:customView];

    UILongPressGestureRecognizer *longPressRecognizer = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressAction:)];
    [customView addGestureRecognizer:longPressRecognizer];
    UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
    [customView addGestureRecognizer:panRecognizer];
}

- (void)longPressAction:(UILongPressGestureRecognizer *)recognizer
{
    if ([recognizer state] == UIGestureRecognizerStateBegan) {
        CustomView *customView = (CustomView *)recognizer.view;
        customView.panRecongnizerEnabled = YES; //panRecongnizerEnabled is CustomView's property
    }
    if ([recognizer state] == UIGestureRecognizerStateEnded) {
        CustomView *customView = (CustomView *)recognizer.view;
        customView.panRecongnizerEnabled = NO;
    }
}

- (void)panAction:(UIPanGestureRecognizer *)recognizer
{
    CustomView *customView = (CustomView *)recognizer.view;
    if (customCell.panRecongnizerEnabled == NO) return;
    NSLog(@"running panAction");
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

最佳答案 您的ViewController需要符合UIGestureRecognizerDelegate.我怀疑你已经这样做过了,否则shouldRecognizeSimultaneouslyWithGestureRecognizer没有任何意义.但你肯定缺少的是将gestureRecognizer的委托设置为viewController:

longPressRecognizer.delegate = self;
panRecognizer.delegate = self;

现在你应该同时接受长按和平移.

注意:我测试时没有任何customView,只是将它们添加到self.view中.至少在这种情况下,上面的代码按预期工作.

点赞