NSView mouseMoved事件有时不会触发

时间:2014-11-20 06:46:25

标签: objective-c cocoa

我有一个视频播放应用,其中显示NSView,跟踪鼠标坐标,以显示用户在某个区域上空盘旋时的位置。

这种方法在70%的情况下完美无缺,但它根本不会发射。最可能发生这种情况的时间似乎是第一次将鼠标放入视图内部并将鼠标悬停在该区域之外然后再次返回内部时。

NSView子类中的代码如下:

- (void)viewDidMoveToWindow
{
    if ([self window]) {
        [self resetTrackingRect];
    }
}

- (void)clearTrackingRect
{
    if (rolloverTrackingRectTag > 0)
    {
        [self removeTrackingRect:rolloverTrackingRectTag];
        rolloverTrackingRectTag = 0;
    }
}

- (void)resetTrackingRect
{
    [self clearTrackingRect];
    rolloverTrackingRectTag = [self addTrackingRect:[self visibleRect]
                                          owner:self userData:NULL assumeInside:NO];
}

- (void)resetCursorRects
{
    [super resetCursorRects];
    [self resetTrackingRect];
}

- (void)mouseEntered:(NSEvent *)theEvent
{
    // Only ask for mouse move events when inside rect because they are expensive
    [[self window] setAcceptsMouseMovedEvents:YES];
    [[self window] makeFirstResponder:self];

    // Tells the observer to show the time view
    [[NSNotificationCenter defaultCenter] postNotificationName:@"MWTimelineHover" object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys:theEvent,@"event",nil]];
}

- (void)mouseExited:(NSEvent *)theEvent
{
    [[self window] setAcceptsMouseMovedEvents:NO];
    [[self window] resignFirstResponder];

    // Tells the observer to hide the time view
    [[NSNotificationCenter defaultCenter] postNotificationName:@"MWTimelineHoverLeave" object:self];
}

- (void)mouseMoved:(NSEvent *)theEvent
{
    [super mouseMoved:theEvent];

    // Tells the observer to show the time view
    [[NSNotificationCenter defaultCenter] postNotificationName:@"MWTimelineHover" object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys:theEvent,@"event",nil]];
}

注意:在它停止的情况下,不会调用mouseExited并且视图没有丢失firstResponder状态。我也没有拖动鼠标,只是正常移动它。

1 个答案:

答案 0 :(得分:2)

您需要使用NSTrackingArea。这是参考NSTrackingArea Class Reference

- (void)commonInit {
    CGRect rect = CGRectMake(0.0f, 0.0f, self.frame.size.width, self.frame.size.height);
    NSTrackingAreaOptions options = NSTrackingActiveInKeyWindow | NSTrackingMouseMoved | NSTrackingInVisibleRect;
    _trackingArea = [[NSTrackingArea alloc] initWithRect:rect options:options owner:self userInfo:nil];
    [self addTrackingArea:_trackingArea];
}

希望它对你有所帮助。