I wan开发者_如何学编程t to detect scroll gestures (two fingers on trackpad). How should i do that?
Looks like you want to override your view's scrollWheel:
method. You can use the NSEvent
's deltaX
and deltaY
methods to get how much the user has scrolled by.
Code:
@implementation MyView
- (void)scrollWheel:(NSEvent *)theEvent {
NSLog(@"user scrolled %f horizontally and %f vertically", [theEvent deltaX], [theEvent deltaY]);
}
@end
You also may want to take a look at the Handling Trackpad Events Guide. This will show you how to capture custom gestures, in addition to standard ones.
You should do that by implementing touch event methods of NSView
in your custom subclass.
These methods are :
- (void)touchesBeganWithEvent:(NSEvent *)event;
- (void)touchesMovedWithEvent:(NSEvent *)event;
- (void)touchesEndedWithEvent:(NSEvent *)event;
- (void)touchesCancelledWithEvent:(NSEvent *)event;
The NSEvent
object coming along as a paramter contains informations about the touches involded. In particular, you may retrieve them using :
-(NSSet *)touchesMatchingPhase:(NSTouchPhase)phase inView:(NSView *)view;
Also, in the custom view subclass, you must first set it like this :
[self setAcceptsTouchEvents:YES];
in order to recieve such events.
To detect the scrollWheel event, use - (void)scrollWheel:(NSEvent *)theEvent method.
- (void)scrollWheel:(NSEvent *)theEvent
{
//implement what you want
}
The above method will be called when you scroll using the scroll wheel from your mouse or the two finger gesture from the trackpad.
If your question is to determine if the scrollWheel event is generated by mouse or trackpad, then according to Apple's documentation, this is not possible. Although here is a work around,
- (void)scrollWheel:(NSEvent *)theEvent
{
if([theEvent phase])
{
// theEvent is generated by trackpad
}
else
{
// theEvent is generated by mouse
}
}
You might also use -(void)beginGestureWithEvent:(NSEvent *)event;
and -(void)endGestureWithEvent:(NSEvent *)event
. These methods are called before and after the -(void)scrollWheel:(NSEvent *)theEvent
respectively.
There is a case when this will not work - if you use the two finger gesture faster and take your fingers out of the trackpad pretty fast, then you might have issues here - (Memory is not getting released)
精彩评论