Cocoa - 当按下某个键时,NSCursor将重置为默认光标

时间:2015-03-10 15:43:54

标签: objective-c cocoa nscursor

我正在开发一个具有完全大小的NSOpenGLView窗口的应用程序。我正在使用[view addCursorRect]和[cursor set]来显示自定义光标,但是当我按下键盘上的任意键时,光标会重置为默认箭头。我还尝试重写resetCursorRects并在按下某个键时调用invalidateCursorRects,这会导致闪烁的光标。

当我单击视图中的任意位置时,光标会切换回我的自定义光标,所以我想键盘会以某种方式按下我的视图。当我按一个键时,有什么方法可以阻止视图变得没有焦点吗?

1 个答案:

答案 0 :(得分:0)

当您需要重置呼叫时需要记住光标设置+,例如refreshCursor方法。示例实现:

- (void)refreshCursor
{
    NSCursor *cursor = nil;
    if ([self graphic]) {
        cursor = [graphic hoverCursorForPoint:[self mousePosition]];
    } else if ([self group]){
        cursor = [NSCursor openHandCursor];
    }
    [self setHoverCursor:cursor];
    [self refresh];
}

- (void)updateTrackingAreas
{
    [super updateTrackingAreas];
    [self removeTrackingArea:[self trackingArea]];
    NSTrackingArea *area = [[NSTrackingArea alloc] initWithRect:[self visibleRect]
                                                        options:NSTrackingActiveAlways|NSTrackingMouseEnteredAndExited|NSTrackingMouseMoved
                                                          owner:self userInfo:nil];
    [self setTrackingArea:area];
    [self addTrackingArea:[self trackingArea]];
}

- (void)setCursorRects
{
    [self discardCursorRects];
    if ([self hoverCursor]) {
        [self addCursorRect:[self visibleRect] cursor:[self hoverCursor]];
    }
}

- (void)setHoverCursor:(NSCursor *)hoverCursor {
    if (_hoverCursor != hoverCursor) {
        _hoverCursor = hoverCursor;
        [self setCursorRects];
    }
}

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

- (void)mouseExited:(NSEvent *)event
{
    [[NSCursor currentSystemCursor] set];
}

- (void)mouseEntered:(NSEvent *)event
{
}

- (void)mouseMoved:(NSEvent *)event
{
    [self refreshCursor];
}

- (void)keyUp:(NSEvent *)event
{
  [self refreshCursor];
}

//allow key events
- (BOOL)acceptsFirstResponder
{
    return YES;
}