cocoaswift2xcode7nsslider

Ask NSSlider if the user still has the mouse button pressed? (swift)


Hi I'm implementing a subclass of NSSlider and NSSliderCell in swift, I would like to check/retrieve the _scFlags.isPressed property from NSSliderCell, I found that there is a 'hack' in Objective-C to do it when calling from another class (which is not really needed if you subclass NSSlider in Objective-C):

http://www.cocoabuilder.com/archive/cocoa/54913-nsslider.html

However, in swift, when I search in the API (AppKit -> NSSliderCell), I can find a struct which I suppose is the one I need, and nothing else but the init() inside:

public struct __sliderCellFlags {
    public init()
}

and I can't even call it from the subclass. All these show as error:

self.__sliderCellFlags 
self._scFlags
super.__sliderCellFlags
super._scFlags

Am I missing something? Is there a different way to call these properties?


Solution

  • Use Objective-C to implement a category on NSSliderCell which has a property to access the struct data and use the property from Swift.

    NSSlider+FlagsAccessor.h

    @interface NSSlider (FlagsAccessor)
    
    @property (nonatomic, readonly) BOOL isPressed;
    
    @end
    

    NSSlider+FlagsAccessor.m

    #import "NSSlider+FlagsAccessor.h"
    
    @interface NSSliderCell (FlagsAccessor)
    
    @property (nonatomic, readonly) BOOL isPressed;
    
    @end
    
    @implementation NSSlider (FlagsAccessor)
    
    - (BOOL)isPressed
    {
        NSSliderCell *cell = self.cell;
    
        return cell.isPressed;
    }
    
    @end
    
    @implementation NSSliderCell (FlagsAccessor)
    
    - (BOOL)isPressed
    {
        return self->_scFlags.isPressed == 1;
    }
    
    @end
    

    Then to use It from Swift just call self.isPressed. Here's a sample project.

    Don't forget to import your category header in your bridging header (Xcode will prompt you to create a bridging header when you add Objective-C code to a Swift project).