关于UIGestures的困惑 - 消息接收者

时间:2015-03-20 15:46:41

标签: ios objective-c

我无法理解我做错了什么

为什么velocityInView:self.view& locationInView发送到UILongPressGestureRecognizer但不发送到UIPanGestureRecognizer

    UILongPressGestureRecognizer *cursorMode =  [[UILongPressGestureRecognizer alloc] 
                                          initWithTarget:self action:@selector(pan:)];
    cursorMode.minimumPressDuration = 0.35;
    [self.Row2View addGestureRecognizer:cursorMode];


- (void)pan:(UIPanGestureRecognizer *)gesture {

    float position = round([gesture locationInView:self.view].x);
    NSLog(@"%f", position);

    CGPoint velocity = [gesture velocityInView:self.view];

    if(velocity.x* _lastGestureVelocity.x > 0)
    {
        NSLog(@"gesture went in the same direction");
    }
    else
    {
        NSLog(@"gesture went in the opposite direction");
    }

    _lastGestureVelocity = velocity;
}

错误: ***由于未捕获的异常终止应用' NSInvalidArgumentException',原因:' - [UILongPressGestureRecognizer velocityInView:]:无法识别的选择器发送到实例0x6080001b0300&# 39;

2 个答案:

答案 0 :(得分:1)

通过创建cursorMode作为平移手势识别器(我认为是你的意思),或重命名pan:方法(到longPress :),并使用长按gr进行参数化来修复。

现在,代码分配长按gr:

UILongPressGestureRecognizer *cursorMode = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];

但是将参数转换为pan:UIPanGestureRecognizer,并向其发送velocityInView:消息。这会在运行时崩溃,因为正如你所指出的那样,它会被发送到长按gr。

编辑 - 根据评论,似乎功能目标是在识别出长按后跟踪动作。这可以在不使用平移手势的情况下完成,方法是自己保持位置状态:

@property(assign,nonatomic) CGPoint lastLocation;

UILongPressGestureRecognizer *cursorMode =  [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
cursorMode.minimumPressDuration = 0.35;
[self.Row2View addGestureRecognizer:cursorMode];

- (void)longPress:(UILongPressGestureRecognizer *)gr {
    CGPoint location = [gr locationInView:gr.view];
    // you can compute the change in location like this
    CGPoint delta = CGPointMake(location.x-self.lastLocation.x, location.y-self.lastLocation.y);

    // do whatever you want with location or delta, then at the end...
    self.lastLocation = location;
}

请注意,坐标系的选择是我们传递给locationInView:的视图的结果。通过传递gr.view作为建议的代码,我们将跟踪中获取手势的视图。另一种常见的坐标选择是在视图的超视图中跟踪平移。

答案 1 :(得分:0)

-(CGPoint)velocityInView:(UIView *)viewUIPanGestureRecognizer但不是UILongPressGestureRecognizerUIGestureRecognizer的方法,这就是您的应用崩溃的原因。