Gra*_*son 3 cocoa objective-c event-handling
我试图能够检测到何时按住鼠标而不是单击鼠标.这就是我所拥有的,但我希望能够检测到被按住的鼠标,而不是点击次数.
-(void)mouseDown:(NSEvent *)event;
{
//instead of clickCount I want my if statement to be
// if the mouse is being held down.
if ([event clickCount] < 1)
{
}
else if ([event clickCount] > 1)
{
}
}
Run Code Online (Sandbox Code Playgroud)
Ant*_*set 10
从OS X 10.6开始,您可以从任何地方使用NSEvent的pressedMouseButtons方法:
NSUInteger mouseButtonMask = [NSEvent pressedMouseButtons];
BOOL leftMouseButtonDown = (mouseButtonMask & (1 << 0)) != 0;
BOOL rightMouseButtonDown = (mouseButtonMask & (1 << 1)) != 0;
Run Code Online (Sandbox Code Playgroud)
该方法返回当前向下的鼠标按钮的索引作为掩码.1 << 0对应于鼠标左键,1 << 1鼠标右键1 << n,n> = 2对应其他鼠标按钮.
有了这个,没有必要赶mouseDown:,mouseDragged:或mouseUp:事件.
大概您想检测鼠标是否被按住一段时间。这非常简单;它只需要一个计时器。
在您的 中mouseDown:,您启动一个计时器,该计时器将在您选择的时间段后触发。您需要将其粘贴到 ivar 中,因为您还将在mouseUp:
- (void)mouseDown: (NSEvent *)theEvent {
mouseTimer = [NSTimer scheduledTimerWithTimeInterval:mouseHeldDelay
target:self
selector:@selector(mouseWasHeld:)
userInfo:theEvent
repeats:NO];
}
Run Code Online (Sandbox Code Playgroud)
在 中mouseUp:,销毁计时器:
- (void)mouseUp: (NSEvent *)theEvent {
[mouseTimer invalidate];
mouseTimer = nil;
}
Run Code Online (Sandbox Code Playgroud)
如果计时器触发,那么您就知道鼠标按钮已按下指定的时间段,并且您可以采取任何您喜欢的操作:
- (void)mouseWasHeld: (NSTimer *)tim {
NSEvent * mouseDownEvent = [tim userInfo];
mouseTimer = nil;
// etc.
}
Run Code Online (Sandbox Code Playgroud)