我想检测滚动手势(触控板上的两个手指)。我该怎么做?
3 回答
看起来您想覆盖视图的scrollWheel:
方法。您可以使用NSEvent
'sdeltaX
和deltaY
方法来获取用户滚动了多少。
代码:
@implementation MyView
- (void)scrollWheel:(NSEvent *)theEvent {
NSLog(@"user scrolled %f horizontally and %f vertically", [theEvent deltaX], [theEvent deltaY]);
}
@end
您可能还想查看处理触控板事件指南。除了标准手势之外,这将向您展示如何捕获自定义手势。
您应该通过NSView
在自定义子类中实现触摸事件方法来做到这一点。这些方法是:
- (void)touchesBeganWithEvent:(NSEvent *)event;
- (void)touchesMovedWithEvent:(NSEvent *)event;
- (void)touchesEndedWithEvent:(NSEvent *)event;
- (void)touchesCancelledWithEvent:(NSEvent *)event;
作为参数出现的NSEvent
对象包含有关所涉及的触摸的信息。特别是,您可以使用以下方法检索它们:
-(NSSet *)touchesMatchingPhase:(NSTouchPhase)phase inView:(NSView *)view;
此外,在自定义视图子类中,您必须首先将其设置为:
[self setAcceptsTouchEvents:YES];
为了接收这样的事件。
要检测 scrollWheel 事件,请使用 - (void)scrollWheel:(NSEvent *)theEvent 方法。
- (void)scrollWheel:(NSEvent *)theEvent
{
//implement what you want
}
当您使用鼠标滚轮或触控板的两指手势滚动时,将调用上述方法。
如果您的问题是确定 scrollWheel 事件是由鼠标还是触控板生成的,那么根据 Apple 的文档,这是不可能的。虽然这是一个解决方法,
- (void)scrollWheel:(NSEvent *)theEvent
{
if([theEvent phase])
{
// theEvent is generated by trackpad
}
else
{
// theEvent is generated by mouse
}
}
您也可以使用-(void)beginGestureWithEvent:(NSEvent *)event;
and -(void)endGestureWithEvent:(NSEvent *)event
。这些方法分别在 之前和之后调用-(void)scrollWheel:(NSEvent *)theEvent
。
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)