如何中止NSStepper自动重复?

时间:2016-03-04 00:41:04

标签: macos cocoa mouseevent

我有一个自动重复NSStepper,我想在收到某个NSNotification时停止跟踪。

一个想法是从接收通知的方法发送[_stepper setAutorepeat: NO]。这不起作用。我想步进器只在跟踪开始时检查自动重复标志。

然后我想我可以继承NSStepperCell,并使用覆盖-[NSCell continueTracking:at:inView:]来中止跟踪。但是,显然当步进器在没有鼠标移动的情况下自动重复时,不会调用该方法。

我是否需要完全重写trackMouse:inRect:ofView:untilMouseUp:?我想当鼠标移入或移出时我必须处理步进器的突出显示部分,并且我看不到任何公共API甚至可以找出突出显示的部分。

1 个答案:

答案 0 :(得分:0)

我最后发布了鼠标活动。我将NSStepperCell子类化为观察通知和发布事件的便利位置。

@interface AbortableStepperCell : NSStepperCell
{
    BOOL    _isTracking;
    BOOL    _isObserverInstalled;
}


@implementation AbortableStepperCell

- (void) dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver: self];

    [super dealloc];
}

- (BOOL)startTrackingAt: (NSPoint) startPoint
    inView: (NSView *) controlView
{
    _isTracking = YES;

    if ( ! _isObserverInstalled )
    {
        [[NSNotificationCenter defaultCenter]
            addObserver: self
            selector: @selector(abortTracking:)
            name: @"AbortMouseTracking"
            object: nil];

        _isObserverInstalled = YES;
    }

    return [super startTrackingAt: startPoint inView: controlView];
}

- (void) abortTracking: (NSNotification*) note
{
    if (_isTracking)
    {
        NSWindow* myWindow = self.controlView.window;
        NSGraphicsContext* gc =
            [NSGraphicsContext graphicsContextWithWindow: myWindow];

        NSEvent* upEvent = [NSEvent
            mouseEventWithType: NSLeftMouseUp
            location: NSZeroPoint
            modifierFlags: 0
            timestamp: 0.0
            windowNumber: myWindow.windowNumber
            context: gc
            eventNumber: 0
            clickCount: 1
            pressure: 0.0f ];

        if (upEvent)
        {
            [NSApp postEvent: upEvent atStart: YES];
        }
    }
}

- (void)stopTracking:(NSPoint)lastPoint
        at:(NSPoint)stopPoint
        inView:(NSView *)controlView
        mouseIsUp:(BOOL)flag
{
    _isTracking = NO;

    [super stopTracking: lastPoint
            at: stopPoint
            inView: controlView
            mouseIsUp: flag];
}

@end