与Lion相同的swipeWithEvent

时间:2011-07-29 13:40:00

标签: objective-c cocoa osx-lion

在雪豹中,有一个用于滑动事件的手势识别器:

- (void)swipeWithEvent:(NSEvent *)event {
    CGFloat x = [event deltaX];

    if (x != 0) {
        (x > 0) ? [self goBack] : [self goForward];
    }
}

是否有一个等同物检测到两个手指轻扫,就像Safari应用程序在狮子会中导航页面一样?

2 个答案:

答案 0 :(得分:1)

我最终从this commit推断出有用的信息并在我自己的项目中实现:

    #define kSwipeMinimumLength 0.3

    - (void)swipeWithEvent:(NSEvent *)event {
    CGFloat x = [event deltaX];
    //CGFloat y = [event deltaY];

    if (x != 0) {
        (x > 0) ? [self goBack] : [self goForward];
    }
}

- (void)beginGestureWithEvent:(NSEvent *)event
{
    NSSet *touches = [event touchesMatchingPhase:NSTouchPhaseAny inView:nil];

    self.twoFingersTouches = [[NSMutableDictionary alloc] init];

    for (NSTouch *touch in touches) {
        [twoFingersTouches setObject:touch forKey:touch.identity];
    }
}

- (void)endGestureWithEvent:(NSEvent *)event
{
    if (!twoFingersTouches) return;

    NSSet *touches = [event touchesMatchingPhase:NSTouchPhaseAny inView:nil];

    // release twoFingersTouches early
    NSMutableDictionary *beginTouches = [twoFingersTouches copy];
    self.twoFingersTouches = nil;

    NSMutableArray *magnitudes = [[NSMutableArray alloc] init];

    for (NSTouch *touch in touches) 
    {
        NSTouch *beginTouch = [beginTouches objectForKey:touch.identity];

        if (!beginTouch) continue;

        float magnitude = touch.normalizedPosition.x - beginTouch.normalizedPosition.x;
        [magnitudes addObject:[NSNumber numberWithFloat:magnitude]];
    }

    // Need at least two points
    if ([magnitudes count] < 2) return;

    float sum = 0;

    for (NSNumber *magnitude in magnitudes)
        sum += [magnitude floatValue];

    // Handle natural direction in Lion
    BOOL naturalDirectionEnabled = [[[NSUserDefaults standardUserDefaults] valueForKey:@"com.apple.swipescrolldirection"] boolValue];

    if (naturalDirectionEnabled)
        sum *= -1;

    // See if absolute sum is long enough to be considered a complete gesture
    float absoluteSum = fabsf(sum);

    if (absoluteSum < kSwipeMinimumLength) return;

    // Handle the actual swipe
    if (sum > 0) 
    {
        [self goForward];
    } else
    {
        [self goBack];
    }


}

它没有100%经过测试,但你明白了。

答案 1 :(得分:-2)

是。请参阅AppKit release notes。 (无论如何,你应该从头到尾阅读它们。)